简体   繁体   中英

React OnChange pass ID or Event

I want to pass the id and value of a textfield to a function on onChange event.

I have tried a bunch of different things but i cant return the event from onChange because it only passes the value.

My function

    const handleFieldChange = (value: any, name: string) =>
    setFields({
        ...fields,
        [name]: value,
    });

And my textfield

<TextField id="test" label="Test" onChange={(event) => handleFieldChange(event, "test")} defaultValue="Test" />

Because the "event" only contains the value and not the actual event i have to pass the ID separately and i cant just do onChange={handleFieldChange}

This seems like a ugly solution because i have hundreds of TextFields

Considering that your event only contains the value and not the actual event, the issue most likely relies within your TextField component. Most likely the onChange implementation returns event.target.value instead of just event .

you can access the id prop of the text field without passing as 2nd argument

const handleFieldChange = (event: React.FormEvent<HTMLInputElement>) => {
    const {id: name, value} = event.currentTarget;
    setFields({
        ...fields,
        [name]: value,
    });
}

HTML

<TextField 
    id="test" // IMP! This is used in the handler 
    label="Test" 
    onChange={handleFieldChange} 
    defaultValue="Test" 
/>

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