温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

react中同级组件的传值方法

发布时间:2020-12-22 09:19:04 来源:亿速云 阅读:490 作者:小新 栏目:web开发

小编给大家分享一下react中同级组件的传值方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

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

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>
<h5 style={{color:this.state.color}}>我是第一个子组件</h5>
<button onClick={this.handlecolor.bind(this)}>改变第二个子组件颜色</button>       
//给第一个子组件绑定一个方法,点击就触发,注意要绑定this
</div>
)
}
}
class Childtwo extends React.Component{
constructor(props){
super(props);
}
render(props){
return(
<h5 style={{color:this.props.co}}>我是第二个子组件</h5>               
//利用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中同级组件的传值方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI