首页 > 解决方案 > 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 属性根本无法识别。为什么?

标签: javascriptreactjstypescriptdomecmascript-6

解决方案


您可以通过 访问它们e.target.dataset。但我建议你应用更多类似 React 的方式。

<Input
    value={values.test}
    onChange={() => handleInput({ name, label, index: 0 })}
/>
const handleInput = ({ name, label, index }) => {
    setValues({
       ...
    });
};

推荐阅读