react 兄弟组件如何调用对方的方法示例
2018-10-23 10:34
1291 查看
最近有一个场景是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;
到这里就可以实现调用兄弟组件,其实还是用父组件做了中间传递。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- Vue兄弟组件之间如何调用对方的方法
- vue.js中父组件调用子组件的内部方法示例
- vue组件之间的通信以及如何在父组件中调用子组件的方法和属性
- GridView等组件绑定后台数据源列的绑定方法,onclick方法调用中含有Eval绑定如何调用js方法
- angular4中父组件如何调用子组件的方法
- 父组件如何调用子组件中的方法和属性
- reactjs--父组件调用子组件的内部方法(转载)
- Vuejs 2.0 子组件访问/调用父组件的方法(示例代码)
- 如何使用沃顿研究数据中心(WRDS,CRSP)查询美股历史交易数据(R语言的调用方法以及代码示例)
- 在React中如何使用复合组件中的方法?
- 如何“正确”编写React组件?我们总结了一套满意的方法
- vue组件之间的通信以及如何在父组件中调用子组件的方法和属性
- react-native中ListView组件点击跳转的方法示例
- vue中子组件调用兄弟组件方法
- 子组件如何调用父组件中的方法和属性
- Spark组件之Spark Streaming学习6--如何调用Dstream里面的getOrCompute方法?
- 如何使用单元测试 测试WEB组件方法中的含有Session、Cookie等HttpContext功能调用的方法?
- 学习Altas 笔记[js调用重载的方法出错,如何处理]
- 如何动态调用DLL中类的方法以及属性 (转载)
- 如何调用IDispatch接口的方法和属性