首页 > 解决方案 > 从开关切换获取自定义属性值

问题描述

我正在尝试获取属性“data-id”的值。但是当我尝试从 onchange 事件处理程序中获取 'data-id' 的值时。我得到一个空值。

 function handleChange(event, e, id) {
            const currentID = e.target.getAttribute('data-id');
}

return(
settings.map(item => {
                    return (
                        <div>
                                <div>
                                    <Switch
                                        checked={item.value}
                                        color="primary"
                                        name="checkedB"
                                        inputProps={{ "aria-label": "primary checkbox" }}
                                        onChange={(event, e) => handleChange(event, e, item.ltbAppSettingID)}
                                        id={"firmSwitch-"+item.settingName}
                                        data-id={item.settingName}
                                    />
                                    <label class="checkLabel" htmlFor={item.ltbAppSettingID}>

                                        <span>{item.name}</span>
                                    </label>
                                </div>
                            }
)

标签: reactjsswitch-statement

解决方案


根据MDN 文档,onchange 全局处理程序接受一个也是唯一的参数,即事件。你给它两个(event,和e)。

尝试替换为:

 function handleChange(e, id) {
            const currentID = e.target.getAttribute('data-id');
}

return(
settings.map(item => {
                    return (
                        <div>
                                <div>
                                    <Switch
                                        checked={item.value}
                                        color="primary"
                                        name="checkedB"
                                        inputProps={{ "aria-label": "primary checkbox" }}
                                        onChange={(e) => handleChange(e, item.ltbAppSettingID)}
                                        id={"firmSwitch-"+item.settingName}
                                        data-id={item.settingName}
                                    />
                                    <label class="checkLabel" htmlFor={item.ltbAppSettingID}>

                                        <span>{item.name}</span>
                                    </label>
                                </div>
                            }
)

编辑:没有意识到这是一个MaterialUI 开关组件

正如您从链接中看到的那样,您不能像使用 vanilla JS 那样向这些组件添加任何属性。如果您出于某种原因必须检索它,恐怕您将不得不将其存储在其他地方。


推荐阅读