标签:form .text sep table syn 内容 ica web forum
最近有一个场景是Child2组件点击让Child1组件里面的state的值发生改变,Child1是一个公用组件,把里面的state值改为props传递,修改内容太多,容易出错,就想找其他的方法来解决兄弟组件调用方法问题,下面看代码:
Child1 是第一个子组件
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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是兄弟组件;
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | class Child2 extends React.Component { constructor(props) {  super(props);  this.state = {  }; } render() {  return(   <div onClick={this.props.onClick}>Child2</div>  ); }} | 
home 父组件
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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>  ); }} | 
分析
到这里就可以实现调用兄弟组件,其实还是用父组件做了中间传递。
标签:form .text sep table syn 内容 ica web forum
原文地址:https://www.cnblogs.com/xanthedsf/p/10163949.html