• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

react中同级组件如何传值?

react 搞代码 4年前 (2021-12-28) 22次浏览 已收录 0个评论

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>
<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 <em style="color:transparent">来源[email protected]搞@^&代*@码网</em>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的相关知识,请查阅 搞代码网 !!

以上就是react中同级组件如何传值?的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:react中同级组件如何传值?
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址