我需要设置多个数据属性,其中包含自定义信息。不幸的是,这不起作用:
<p data={"Very important info"} onClick={this.accessAttributes}
data2={"A lot of important info"}></p>
accessAttributes = e =>{
ToggleFavorito = (e) =>{
let data1=e.currentTarget.data;
let data2=e.currentTarget.data2;
console.log(data1, data2)
}
它返回“未定义”。
我怎样才能做到这一点?
最佳答案
如果您的目的是使用 data 或 data2 作为普通的 html 属性,您可以使用
accessAttributes = e =>{
let data1=e.currentTarget.getAttribute("data");
let data2=e.currentTarget.getAttribute("data2")
console.log(data1, data2)
}
如果您希望它们为 data-attributes ,您可以使用
<p data-one={"Very important info"} onClick={this.accessAttributes}
data-two={"A lot of important info"}></p>
accessAttributes = e =>{
let data1=e.currentTarget.dataset.one
let data2=e.currentTarget.dataset.two
console.log(data1, data2)
}
顺便说一下,如果你的p
处于渲染状态,p里面没有内容可以点击。或者至少它应该有一个高度和宽度。
class App extends React.Component {
constructor(props) {
super(props)
}
accessAttributes = e =>{
let data1=e.currentTarget.getAttribute("data");
let data2=e.currentTarget.getAttribute("data2")
console.log(data1, data2)
}
accessAttributes2 = e =>{
let data1=e.currentTarget.dataset.one;
let data2=e.currentTarget.dataset.two;
console.log(data1, data2)
}
render() {
return (
<div>
<p data={"Very important info"} onClick={this.accessAttributes}
data2={"A lot of important info"}>x</p>
<p data-one={"Very important info"} onClick={this.accessAttributes2}
data-two={"A lot of important info"}>y</p>
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
关于reactjs - React 中的多个数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55657372/