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;

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值