当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react 兄弟组件如何调用对方的方法示例

react 兄弟组件如何调用对方的方法示例

2018年11月05日  | 移动技术网IT编程  | 我要评论

最近有一个场景是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;

到这里就可以实现调用兄弟组件,其实还是用父组件做了中间传递。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网