从子组件更新状态

时间:2020-04-18 06:13:31

标签: reactjs react-hooks

我无法解决这个问题。我想从子组件中更新状态

const Main = () => {
    const [brands] = useState([{ name: "John", age: 20 }, { name: "Mary", age: 10 }]);
    return brands.map(brand => <Child brand={ brand } />)
}

const Child = (props) => {
    const { age } = props.brand;
    return <button onClick={ "how to update age here and make it available in the parent component" } />
}

2 个答案:

答案 0 :(得分:1)

useState挂钩返回状态以及用于设置该状态的函数。您可以将此设置器传递给子组件,然后从那里调用。

const Main = () => {
    const [brands, setBrands] = useState([{ name: "John", age: 20 }, { name: "Mary", age: 10 }]);

const updateState = (brand, indexToUpdate) => {
  const newState = [...brands];
  newState[indexToUpdate] = brand;
  setBrands(newState);
};

    return brands.map((brand, idx) => <Child brand={ brand } updateState} idx={idx} />)
}

const Child = (props) => {
    const { age } = props.brand;
    return <button onClick={() => props.setBrands(props.brand, props.idx) } />
}

答案 1 :(得分:0)

Check this Solution

发送父级国家作为子级的支持 使用Prop方法处理状态更新