小编给大家分享一下react兄弟组件调用对方的案例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
最近有一个场景是Child2组件点击让Child1组件里面的state的值发生改变,Child1是一个公用组件,把里面的state值改为props传递,修改内容太多,容易出错,就想找其他的方法来解决兄弟组件调用方法问题,下面看代码:
Child1 是第一个子组件
class Child1 extends React.Component {
constructor(props) {
super(props);
this.state = {
text:'Child1'
};
}
onChange=()=>{
this.setState({
text:'Child1 onChange'
})
}
componentDidMount(){
this.props.onRef&&this.props.onRef(this)
}
render() {
return (
<div>{this.state.text}</div>
);
}
}
是第二个子组件,和Child1是兄弟组件;
class Child2 extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div onClick={this.props.onClick}>Child2</div>
);
}
}
home 父组件
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
onRef=(ref)=>{
this.child1=ref;
}
render() {
return (
<div className="home">
<Child1 onRef={this.onRef}/>
<Child2 onClick={
()=>{
this.child1.onChange&&this.child1.onChange()
}
} />
</div>
);
}
}
分析
第一步:在Child1组件的componentDidMount生命周期里面加上this.props.onRef(this),把Child1都传递给父组件,
第二步父组件里面 <Child1 onRef={this.onRef}/> this.onRef方法为onRef=(ref)=>{this.child1=ref;};
第三步 Child2组件触发一个事件的时候,就可以直接这样调用this.child1.onChange(),Child1组件里面就会直接调用onChange函数,修改text为Child1 onChange;
以上是“react兄弟组件调用对方的案例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。