reactjs - 从开关切换获取自定义属性值
问题描述
我正在尝试获取属性“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>
}
)
解决方案
根据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 那样向这些组件添加任何属性。如果您出于某种原因必须检索它,恐怕您将不得不将其存储在其他地方。
推荐阅读
- javascript - 如何制作一个 js 代码,仅当用户满足“if”条件时才允许用户查看他们的页面?
- php - 无法将任何样式表添加到 prestashop 1.7 中的模块
- javascript - 现在服务中的这段代码是什么意思?
- python - 具有字符串格式的python正则表达式模式
- javascript - 点击提交按钮后输入文本区域的文本
- python - 如何摆脱 CSV 中的撇号但保持前导 0?
- arrays - 将嵌套结构中的数组附加到另一个嵌套结构中的另一个数组
- r - ggplot 图形不输出 Jupytr Notebook (R/tidyverse)
- angularjs - 从 angularjs 升级到 angular 时替换 ng-include 的最佳实践?
- azure-blob-storage - Azure 表单识别器培训未找到数据