简体   繁体   English

反应 OnChange 传递 ID 或事件

[英]React OnChange pass ID or Event

I want to pass the id and value of a textfield to a function on onChange event.我想将文本字段的 id 和值传递给 onChange 事件的函数。

I have tried a bunch of different things but i cant return the event from onChange because it only passes the value.我尝试了很多不同的东西,但我无法从 onChange 返回事件,因为它只传递值。

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}因为“事件”只包含值而不是实际事件,我必须单独传递 ID,我不能只做 onChange={handleFieldChange}

This seems like a ugly solution because i have hundreds of TextFields这似乎是一个丑陋的解决方案,因为我有数百个 TextField

Considering that your event only contains the value and not the actual event, the issue most likely relies within your TextField component.考虑到您的event仅包含值而不包含实际事件,问题很可能依赖于您的 TextField 组件。 Most likely the onChange implementation returns event.target.value instead of just event .很可能 onChange 实现返回event.target.value而不仅仅是event

you can access the id prop of the text field without passing as 2nd argument您可以访问文本字段的 id 属性而无需作为第二个参数传递

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

HTML HTML

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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