onRef

作者: lovelydong | 来源:发表于2019-11-13 15:45 被阅读0次

原理:onRef 通讯原理就是通过 props 的事件机制将组件的 this(组件实例)当做参数传到父组件,父组件就可以操作子组件的 state 和方法

子组件

export default class Child extends React.Component {
  state={
      name:'这是组件Child的name 值'
  }

  componentDidMount(){
    this.props.onRef(this)
    console.log(this) // ->将Child传递给父组件this.props.onRef()方法
  }

  click = () => {
    this.setState({name:'这是组件click 方法改变Child改变的name 值'})
  };

  render() {
    return (
      <div>
        <div>{this.state.name}</div>
        <Button type="primary" onClick={this.click}>
          点击改变组件Child的name 值
        </Button>
      </div>
    );
  }
}

父组件

<Child  onRef={this.ChildFourRef}></Child  >

ChildFourRef= (ref)=>{
  console.log('Child的Ref值为')
  // 获取的 ref 里面包括整个组件实例
  console.log(ref)
  // 调用子组件方法
  ref.click()
}

相关文章

网友评论

      本文标题:onRef

      本文链接:https://www.haomeiwen.com/subject/ihzhictx.html