【问题标题】:Update a react components state from its parent从其父级更新反应组件状态
【发布时间】:2017-10-13 10:28:17
【问题描述】:

是否可以通过从其父级调用其成员函数来更新 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>);
  }
}

【问题讨论】:

  • 你能发布完整的课程来确认一下吗?

标签: reactjs


【解决方案1】:

是否可以通过从控制器调用其成员函数来更新 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 挂载时,我们将 state 设置为 data prop 设置的任何值。每当 Child 组件收到 componentWillReceiveProps() 的 props 时,我们都会更新状态。

家长

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>;
  }
}

【讨论】:

  • 嗨,应该是this.props.children[0] 而不是this.child
  • @Xin 不。这只是我为该组件的引用名称选择的任意名称。与 React 道具或状态本身无关。
猜你喜欢
  • 2015-04-23
  • 1970-01-01
  • 2017-09-10
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 2020-01-23
  • 2019-09-17
相关资源
最近更新 更多