reactjs - React 中的多个数据属性

标签 reactjs

我需要设置多个数据属性,其中包含自定义信息。不幸的是,这不起作用:

    <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/

相关文章:

javascript - 如何为 props 设置默认值

javascript - 从 2 个按 id 分组的 JSON 对象创建新的 javascript 对象

javascript - 从本地存储中删除项目后出现未处理的拒绝错误。刷新修复

javascript - Wow.js 与 webpack 和 react

twitter-bootstrap - 使用 react-bootstrap 扩展表内的行

javascript - 在react中动态创建自定义表单组件

javascript - 提交后清除url

javascript - 无法使用react-redux设置属性

node.js - 无法加载在 'flowtype' : Cannot find module 'package.json » eslint-config-react-app' 中声明的插件 'eslint/use-at-your-own-risk' 中的 npm 错误

javascript - 什么是用于 create-react-app 的 webpack.DefinePlugin 的良好替代品?