更改子级内部父级组件的状态

时间:2019-02-20 02:09:44

标签: reactjs

我已经开始学习反应,但找不到我的其中一个问题的答案。

假设我有一个称为main的父组件,其中有状态,其中一个是计数器。

在main内部,我有一个名为secondary的子组件,带有几个按钮。

是否可以使用子组件内部的功能来更改父组件的状态?

如果没有,Redux是否会帮助解决该任务?

谢谢您的澄清

4 个答案:

答案 0 :(得分:4)

您的父组件可以保留一个状态,该状态在constructor中进行了初始化,如下所示:

class Main extends Component {
  constructor (props) {
    super(props)
    this.state = { counter: 0 }
  }
  ...

然后,您想在Main中创建一个增加状态计数器的方法:

  incrementCounter = () => {
    this.setState({ counter: this.state.counter + 1 })
  }

您可以将此函数引用作为道具传递给子组件。因此,您可能会在render的{​​{1}}方法中看到这一点:

Main

然后,在<Child incrementParent={this.incrementCounter} /> 中,您可以随时调用Child-这将调用从this.props.incrementParent()传递给它的函数,该函数将递增Main的状态计数器。

以下是code sandbox ,显示了所有这些内容。其中有一个带有其自身状态计数器的父容器(Main)。有一个Main组件,其中包含3个按钮。每个按钮单击都会增加其 own 计数器,但是 any 按钮单击也会增加父级的计数器。

希望这会有所帮助!

答案 1 :(得分:1)

是的,您可以创建一个更新父状态的函数,并在特定应用需要时通过props,context或redux将其传递下来。

例如使用React钩子

function Parent() {
  const [value, setValue] = useState(1);

  const increment = () => {
    setValue(value + 1);
  }

  return (
    <Child increment={increment} />
  );
}

function Child(props) {
  const { increment } = props;

  return (
    <button onClick={increment} />
  );
}

答案 2 :(得分:0)

class Parent extends Component {
  state = { counter: 0 };

  updateCounter = () => {
    this.setState(prevState => ({
     counter: prevState.counter + 1
    }))
  };

  render() {
    return (
      <>
        <Text>{this.state.counter}</Text>
        <ChildComponent updateCounter={this.updateCounter} />
      </>
    );
  }
}
class ChildComponent extends Component {
  ...
  render() {
    return (<Button onPress={this.props.updateCounter}><Text>{'Press Me!'}</Text></Button>)
  }
}

您应该通过从父母那里更新计数器updateCounter的功能,将该引用传递给ChildComponent

答案 3 :(得分:0)

您可以通过将功能传递给子组件来更新父状态来更新父状态。

在示例中调用updateCounter函数时,可以通过在函数的参数中提供一个运算符countplus来减小或增大minus的值。

class Parent extends Component {
  state = {
    count: 1
  };
  updateCounter = operator => {
    if (["plus", "minus"].includes(operator)) {
      this.state(prevState => ({
        count: prevState.count + (operator === "plus" ? 1 : operator === "minus" ? -1 : 0)
      }));
    }
  }
  render() {
    const { count } = this.state;
    return (
      <Child count={count} updateCounter={this.updateCounter} />
    );
  };
};

const Child = props => (
  <div>
    <button onClick={() => props.updateCounter("minus")}>MINUS</button>
    <button onClick={() => props.updateCounter("plus")}>PLUS</button>
    <h1>{props.count}</h1>
  </div>
);
相关问题