如何在 React Hooks 中触发从子级到父级的状态变化?

cat*_*use 0 javascript reactjs react-hooks

这些在父组件中......

   const [setQuantity, quantity] = useState(1);

   const handleSetQuantity = e => {
      console.log(e.target.value);
      console.log("TEST");

      setQuantity(e.target.value);
    };
Run Code Online (Sandbox Code Playgroud)

我将它传递给子组件,如下所示:

<SomeChildComponent
    setQuantity={e => handleSetQuantity(e)}
    quantity={quantity}
/>
Run Code Online (Sandbox Code Playgroud)

在 - 的里面 :

<select
    onChange={e => props.setQuantity(e)}
    value={props.quantity}
    >
    <option value={1}>1</option>
    <option value={2}>2</option>
    <option value={3}>3</option>
</select>
Run Code Online (Sandbox Code Playgroud)

由于出现“TEST”日志,我可以从孩子那里访问该功能。但是它告诉我:

Uncaught TypeError: setQuantity is not a function
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?如果是这样,从子组件触发的操作更改父状态的正确方法是什么?

Ded*_*Dev 5

您正在传递一个已执行的函数,您应该传递引用。

<SomeChildComponent
    setQuantity={handleSetQuantity}
    quantity={quantity}
/>
Run Code Online (Sandbox Code Playgroud)

还,

const [setQuantity, quantity] = useState(1);

你交换了值和函数的位置,应该是:

const [quantity, setQuantity] = useState(1);