简体   繁体   中英

Trigger onChange event manually

I would like to call my onChange manually.

Here's my select with onChange (I pass onChangeSelect as a prop from parent component)

return(
   <Form Control disabled={disabled}
      <NativeSelect ref={ref} onChange={onChangeSelect}>
       ...

And I'd like to call that onChange every time my variable changes and is empty

useEffect(() => {
    if (requiredSelect[0].length > 0 || id === "root1") { setDisabled(false) }
    else { ref.current.value = ([[], []]); ref.current.onChange ; setDisabled(true); }
}, [requiredSelect])

And here's onChangeSelect in parent component

<Child onChangeSelect={(e) => rootChange(e)}>

and what it does

const rootChange = e => { setRootSelect(e.target.value.split(',')); }

The simplest solution here would be to change the definition of your rootChange function to accept the value instead of the event itself.

const rootChange = value => { setRootSelect(value.split(',')); }

// In parent:
<Child onChangeSelect={rootChange}>

// Select
<NativeSelect ref={ref} onChange={(e) => onChangeSelect(e.target.value)}>

You can trigger the function manually with:

onChangeSelect(whateverValueYouWant); // notice that you need the brackets when calling the function.

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