react子组件与父组件通信

用 function prop 与父组件通信

props

props 本身是不可变的。当我们试图改变 props 的原始值时,React 会报出类型错误的警告,组件的 props 一定来自于默认属性或通过父组件传递而来。

ref

React提供的这个ref属性,表示为对组件真正实例的引用,其实就是ReactDOM.render()返回的组件实例。

  • 在子组件的props里定义function prop
functionProp: () => {},
  • 在constructor里将this传入function prop
constructor(props) {
    super(props);
    this.props.functionProp(this);
  }
  • 在父组件内实例化子组件 SonComponent
  • 在父组件内写子组件的function prop时,将实例化的组件传入,表示对实例化组件的引用
<SonComponent
   functionProp={(ref) => { this.SonComponent = ref; }}
   ...
/>
  • 子组件接受父组件传递的props,在子组件内对传递进来的props赋值给state
componentWillReceiveProps(props) {
    this.setState({ data: props.content });
}
  • 进行一系列数据处理,更改data的值
  • 将data传回父组件
submit = () => {
    return this.state.data;
  }
  • 在父组件需要的地方调用这个方法
this.SonComponent.submit();

猜你喜欢

转载自blog.csdn.net/hannah1116/article/details/82463951