admin管理员组文章数量:1355582
I have this list:
const chosen = (e: any) => console.log(e.target.dataset.value)
...
<ul>
{numbers.map(n => (
<a data-value={n} onClick={chosen}>
<li key={n}>
{n}
</li>
</a>
))}
</ul>
...
It logs undefined
.
Also tried this: console.log(e.target.getAttribute('data-value'))
and it returns null
.
How do I get the value from a
tag?
Stack: TypeScript: 3.8.3, React: 16.13.1
I have this list:
const chosen = (e: any) => console.log(e.target.dataset.value)
...
<ul>
{numbers.map(n => (
<a data-value={n} onClick={chosen}>
<li key={n}>
{n}
</li>
</a>
))}
</ul>
...
It logs undefined
.
Also tried this: console.log(e.target.getAttribute('data-value'))
and it returns null
.
How do I get the value from a
tag?
Stack: TypeScript: 3.8.3, React: 16.13.1
Share Improve this question edited Jul 13, 2020 at 13:17 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Jun 17, 2020 at 15:15 SwixSwix 2,12311 gold badges38 silver badges58 bronze badges 1-
isn't it just
element.getAttribute(attributeName);
? – Red Baron Commented Jun 17, 2020 at 15:20
4 Answers
Reset to default 3In frameworks like React and Vue you generally stay away from reading data from the DOM when possible. In this case, you can capture the value in a function:
const chosen = (e: any, value: any) => console.log(value)
...
<ul>
{numbers.map(n => (
<a key={n} onClick={(event) => { chosen(event, n); }}>
<li>
{n}
</li>
</a>
))}
</ul>
...
You can use the following code to do that:
export default function App() {
function chosen(event) {
const meta = event.target.parentNode.getAttribute("data-value");
console.log(meta);
}
return (
<ul>
{numbers.map((n) => (
<a data-value={n} onClick={chosen}>
<li key={n}>{n}</li>
</a>
))}
</ul>
);
}
li
element should contentin the a
element. Please try this example
import React from "react";
const numbers = [1, 2, 3, 4, 5];
function App() {
function chosen(event) {
event.preventDefault();
console.log(event.target.dataset.value);
}
return (
<ul>
{numbers.map((number) => {
return (
<li key={number}>
<a href="!#" onClick={chosen} data-value={number}>
{number}
</a>
</li>
);
})}
</ul>
);
}
export default App;
And follow the Ross Allen advice
Access attributes from the currentTarget
instead like this :
console.log(e.currentTarget.getAttribute('data-value'))
本文标签: javascriptHow to get dataattribute in ReactStack Overflow
版权声明:本文标题:javascript - How to get data-attribute in React? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744048762a2582029.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论