javascript - React 没有使用 e.target.getAttribute() 方法获取自定义属性
问题描述
我正在尝试在我的 changeHandler 中处理自定义属性。不幸的是,React 无法识别自定义的“data-index”属性。
所有其他标准属性(例如名称、标签等)都被识别。
我究竟做错了什么?
我的输入字段:
<Input
name="test"
label="test 1"
data-index="0"
value={values.test}
onChange={handleInput}
/>
我的 changeHandler (这里的数据索引始终为空):
const handleInput = (e: any) => {
const { value } = e.target;
const dataIndex = e.target.getAttribute('data-index');
setValues({
...
});
};
更新:
我发现 e.target.attributes 输出以下内容。
NamedNodeMap {0: aria-invalid, 1: id, 2: name, 3: type, 4: class, 5: value, aria-invalid: aria-invalid, id: id, name: name, type: type, class: class, …}
0: aria-invalid
1: id
2: name
3: type
4: class
5: value
length: 6
我的 data-index 属性根本无法识别。为什么?
解决方案
您可以通过 访问它们e.target.dataset
。但我建议你应用更多类似 React 的方式。
<Input
value={values.test}
onChange={() => handleInput({ name, label, index: 0 })}
/>
const handleInput = ({ name, label, index }) => {
setValues({
...
});
};
推荐阅读
- php - foreach 中只插入 1 行
- azure - 使用从一个 Azure DF 管道到另一个管道的查找
- sqlalchemy - 如何在 sqlalchemy 中使用 filter_by 而不是等于?
- html - 如何使用delphi在网页上提交表单
- c# - 具有标识的 StructureMap DbContext
- conditional-statements - 如何在基于 AnyLogic 代理的仿真中使用单个条件
- amazon-web-services - AWS SSM 描述实例信息未找到我的实例
- c++ - for循环内的while循环
- django - Django 需要可选表单字段错误
- amp-html - 使用亚马逊和特定产品配置 amp-ad