简体   繁体   English

使用React.js获取数据属性

[英]Getting data attributes with React.js

Why do I have to put data-* in every html child attribute so i won't get undefined by clicking on parent ? 为什么我必须在每个html child attribute放入data-*所以我不会通过单击parentundefined Ie

<li data-item="item-1">
  <img src="../img" alt="img" />
  <p>Some text</p>
</li>

By this example i will get item-1 whenever i click near the borders of <li> but whenever i click either img or text/paragraph i get undefined . 通过这个例子,每当我点击<li>的边界附近时我都会得到item-1但是每当我点击imgtext/paragraph我都会得到undefined But when I set data-item on <li> childs i get normal data value. 但是当我在<li> childs上设置data-item ,我获得了正常的data值。 What? 什么?

PS. PS。 The way i get data-* is for example 我获得data-*的方式是data-*

handleClick(event){
  let data = event.target.dataset['item']
}
...
<li data-item="item-1" onClick={this.handleClick.bind(this)}>...</li>

What am I doing wrong, that I have to put into every <li> child data-* so I won't get undefined on whole <li> block on<Event> ? 我做错了什么,我必须在每个<li>data-*所以我不会on<Event>上的整个<li>on<Event>得到未定义的?

FYI, the problem has nothing to do with React. 仅供参考,这个问题与React无关。 It's how DOM events in browsers work. 这是浏览器中DOM事件的工作方式。 Have a look at this quirksmode.org article to learn more about how event propagation works. 查看这篇quirksmode.org文章 ,了解有关事件传播如何工作的更多信息。

event.target will always refer to the element the event was triggered on. event.target将始终引用触发事件的元素。 So if you click on the <p> element, event.target will refer to that element. 因此,如果单击<p>元素, event.target将引用该元素。 Since <p> doesn't have a data-* attribute you get undefined . 由于<p>没有data-*属性,因此undefined

To always get the element where the handler is bound to (ie the <li> element in your example), use event.currentTarget instead. 要始终获取绑定处理程序的元素(即示例中的<li>元素),请使用event.currentTarget

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM