react中同级组件传值的方法:首先打开相应的前端文件;然后设置共同的父组件传值;接着创建一个子组件,并将数据传递到父组件中;最后使父组件接收值,并传入另一个子组件中即可。

本教程操作环境:Windows7系统、react17.0.1版本,该方法适用于所有品牌电脑。
推荐:《react视频教程》
React同级组件传值

在React中同级组件本身是没有任何关联的,要想有联系只能通过共同的父组件传值,一个子组件将数据传递到父组件中,父组件接收值再传入另一个子组件中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="box"></div>
<script type="text/babel">
//子组件向父组件传值,父组件接收再传递给另一个子组件
class Childone extends React.Component{
constructor(props){
super(props);
this.state={color:"lightblue"}
}
handlecolor(){
this.props.fn("red");
//在触发方法中通过props添加一个新的fn方法,并且将颜色参数red传入父组件
this.setState({color:"red"});
}
render(){
return(
<div>
<h4 style={{color:this.state.color}}>我是第一个子组件</h4>
<button onClick={this.handlecolor.bind(this)}>改变第二个子组件颜色</button>
//给第一个子组件绑定一个方法,点击就触发,注意要绑定this
</div>
)
}
}
class Childtwo extends React.Component{
constructor(props){
super(props);
}
render(props){
return(
<h4 style={{color:this.props.co}}>我是第二个子组件</h4>
//利用prop属性从外界即父组件获取参数,不能用state,state是内部使用的
)
}
}
class Parents extends React.Component{
constructor(props){
super(props);
this.state={childtwocolor:"lightblue"};
}
change(color) {
this.setState({childtwocolor: color});
}
render(props) {
return (
<div>
<Childone fn={(color)=>{this.change(color)}}></Childone>
//第一个子组件的方法fn,将参数red传入函数change中,更新父组件本身的颜色childtwocolor
<Childtwo co={this.state.childtwocolor}></Childtwo>
//第二个子组件获取父组件本身的颜色,当父组件颜色更新时,它也会随之更新
</div>
)
}
}
ReactDOM.render(
<Parents />,
document.getElementById('box')
);
</script>
</body>
</html>以上就是react中同级组件如何传值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号