如何在React 16.3中使用父组件道具设置子组件状态?

时间:2018-05-08 14:00:38

标签: javascript reactjs

我一直在努力构建一个应用程序,其中一个不寻常的场景已经提出让我处理。我必须将props传递给父组件中的子组件,子组件需要将这些props设置为其状态。

<ChildComponent allProps={parentProps}>
  <SomeChildren withProps />
</ChildComponent>

ChildComponent

class ChildComponent extends Component {
  state: {
    someRequiredProps: null
  }
  setStateForThisComponent(propsToSet) {
    this.setState({someRequiredProps: propsToSet});
  }
  componentDidMount() {
    this.props.allProps()
  }
  render() {
    //I know this is incorrect syntax
    return (<div allProps={(propsArg) => this.setStateForThisComponent(propsArg)});
  }
}

通常,我可以使用refs从父组件运行此方法,但由于此ChildComponent是一个非常重用的组件,因此我不想采用refs方法。其他一些解决方案建议我在父组件本身创建状态,并将其作为道具传递给ChildComponent,但这不是我想要实现的。

请让我解决使用父母设置子组件状态的问题。

1 个答案:

答案 0 :(得分:0)

如果您只需要将初始道具设置为状态,则可以在构造函数中执行:

constructor(props) {
  super(props);
  this.state = {
    someRequiredProps: props.someRequiredProps,
  }
}

如果必须更新道具时必须更新状态,则需要使用新的getDerivedStateFromProps方法:

class ChildComponent extends Component {
  state: {
    someRequiredProps: null,
  };
  static getDerivedStateFromProps(nextProps, prevState) {
    return {
      // return the new state based on `nextProps`
      someRequiredProps: nextProps.someRequiredProps,
    };
  }

另请注意docs

  

请注意,如果父组件导致组件重新渲染,即使props没有更改,也会调用此方法。如果您只想处理更改,则可能需要比较新值和以前的值。

相关问题