简体   繁体   中英

How to trigger state change from child to parent in React Hooks?

These are in the parent component...

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

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

      setQuantity(e.target.value);
    };

And I am passing it to child component like so:

<SomeChildComponent
    setQuantity={e => handleSetQuantity(e)}
    quantity={quantity}
/>

Inside the :

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

I am able to access the function from child since the "TEST" log appears. However it tells me that:

Uncaught TypeError: setQuantity is not a function

What am I doing wrong? And if so, what is the right way to change parent state from action triggered by child component?

You are passing an executed function, and you should pass the reference.

<SomeChildComponent
    setQuantity={handleSetQuantity}
    quantity={quantity}
/>

Also,

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

you swapped the places of the value and the function, should be:

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

You can pass the method to your child component directly through props

<SomeChildComponent
    {setQuantity}
    {quantity}
/>

you child components will then be able to use the method as you would in the parent component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM