[英]get data attribute from “root” DOM node in react js
Let's say there is a <div>
somewhere in HTML file:假设在 HTML 文件中某处有一个
<div>
:
I want to pass an attribute data-person-name from that <div>
having id root ,to react element我想从具有 id root的
<div>
传递一个属性data-person-name来反应元素
<div id="root" data-person-name="John"></div>
const element = <h1>Hello,{data-person-name}</h1>;
ReactDOM.render(element, document.getElementById('root'));
Please suggest the right way to do that.请提出正确的方法来做到这一点。
A cleaner way would be to prefix all custom attributes with "data-".一种更简洁的方法是在所有自定义属性前面加上“data-”。 Because there is no known attribute "personName" for a div element and having that is against W3 rules.
因为 div 元素没有已知的属性“personName”并且违反 W3 规则。 The code may look like this:
代码可能如下所示:
<div id="root" data-personName="John"></div>
const element = <h1>Hello,{document.getElementById('root').getAttribute('data-personName')}</h1>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.