最近有一个场景是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> ); } }
分析
到这里就可以实现调用兄弟组件,其实还是用父组件做了中间传递。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
MFC的静态库.lib、动态库.dll(包含引入库.lib)以及Unicode库示例
CTF 刷题记录(一) 白云新闻搜索(手动与自动化SQL注入)
javascript如何使用函数random来实现课堂随机点名方法详解
网友评论