从其父级更新react组件状态

时间:2017-10-13 10:28:18

标签: reactjs

通过从其父级调用其成员函数来更新React组件状态是否可以。类似的东西:

class SomeComp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  } 

  updateState(data) {
    this.setState({ data: data })
  }

  render() {
    return (<div>this.state.data</div>);
  }
}

1 个答案:

答案 0 :(得分:4)

  

通过从控制器调用其成员函数来更新React组件状态是否可以?

是的,你可以这样做,但这是不必要的。通常,您希望通过从父级传递道具来更新子级状态。我已经举例说明了如何从下面的父母那里更新一个孩子。

示例1:

在此示例中,您不需要任何状态。 Parent管理状态并通过props传递对Child的任何更改。这是推荐的方法。

<强>父

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {text: "hello"};
  } 

  render() {
    return <Child data={this.state.text} />;
  }
}

儿童

class Child extends React.Component {    
  render() {
    return <span>{this.props.data}</span>;
  }
}

示例2:

在此示例中,我们使用两个状态,每个组件一个。这对于此实现来说是不必要的,但您仍然可以执行此操作。当Child安装时,我们将状态设置为数据prop设置的任何值。每当Child组件收到componentWillReceiveProps()的道具时,我们都会更新状态。

<强>父

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {text: "hello"};
  } 

  render() {
    return <Child data={this.state.text} />;
  }
}

儿童

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {childText: props.data};
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.data !== this.props.data)
      this.setState({childText: data});
  }

  render() {
    return <span>{this.state.childText}</span>;
  }
}

示例3:

在此示例中,Child组件被赋予ref,然后我们可以使用它来从Parent触发Child函数。通常这是以相反的顺序完成(触发从Child到Parent的功能),但如果需要,您仍然可以执行此操作。这是更手动的方法,与您提出的方法类似。

<强>父

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {text: "hello"};
  }

  triggerUpdate = () => {
    this.child.component.update(this.state.text);
  }

  render() {
    return <Child ref={(el) => this.child = el} data={this.state.text} />;
  }
}

儿童

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {childText: props.data};
  }

  update = (text) => {
    this.state({childText: text});
  }

  render() {
    return <span>{this.state.childText}</span>;
  }
}