react中同级组件如何传值

藏色散人
藏色散人 原创
2020-12-21 10:01:38 1787浏览

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

本教程操作环境:Windows7系统、react17.0.1版本,该方法适用于所有品牌电脑。

推荐:《react视频教程

React同级组件传值

bbdf598b2b7d98df375c1613d3583b8.png

在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中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。