[英]Getting ID from div in React.js
So I'm trying to retrieve data in a div attribute in react. 所以我正在尝试在div属性中检索数据。 JSFiddle shows the problems I'm having.
JSFiddle显示了我遇到的问题。 this.state.value is set to an empty string after the event fires.
事件触发后,this.state.value设置为空字符串。
I started off using the data-* attribute for the div after reading another stack overflow post , but I cannot use jQuery, so I switched to id. 在阅读了另一个堆栈溢出文章之后 ,我开始使用div的data- *属性,但是我无法使用jQuery,所以我切换到了id。 Any ideas?
有任何想法吗?
class GettingAttributes extends React.Component {
constructor(props) {
super(props)
this.state = {value: 'Hello!'};
this.bar = this.bar.bind(this);
}
bar(e){
this.setState({value: e.target.id})
}
render() {
return (
<div id="foo" onClick={this.bar}>
<p>{this.state.value}</p>
</div>
);
}
}
Use 采用
e.currentTarget.id
instead of 代替
e.target.id
.currentTarget will target the element that actually contains the event listener. .currentTarget将定位实际包含事件侦听器的元素。 In your scenario, .target is the p tag with the text in it, which doesn't have an id to set in your state.
在您的方案中,.target是带有文本的p标记,在您的状态中没有要设置的ID。
You can do it by id
as well as data-*
attributes. 您可以通过
id
以及data-*
属性来实现。 But the preferred method is by data-*
attributes. 但是首选方法是使用
data-*
属性。
Please consider this JSFiddle link of your solution. 请考虑您解决方案的这个JSFiddle链接。
You should set ref on the element from which you want to extract the data and then you can use it to set data in state. 您应该在要从中提取数据的元素上设置ref,然后可以使用它来将数据设置为state。 IN code if you replace
onClick={this.bar}
with onClick={this.barById}
then code will extract data from id
while in former case it will extract data from data-*
attributes. 在代码中,如果你更换
onClick={this.bar}
用onClick={this.barById}
然后将代码从数据提取id
,而在前者的情况下它将从数据中提取data-*
属性。
the reason why you are unable to select the id
property is that the current e.target
is the child of the <div>
, which is <p>
. 之所以无法选择
id
属性,是因为当前的e.target
是<div>
的子e.target
,该子元素是<p>
。 Here is a proposed solution that works: 这是一个可行的建议解决方案:
class GettingAttributes extends React.Component {
constructor(props) {
super(props)
this.state = {value: 'Hello!'};
this.bar = this.bar.bind(this);
}
bar(e){
this.setState({value: e.target.id})
}
render() {
return (
<div id="foo" onClick={this.bar}>
{this.state.value}
</div>
);
}
}
ReactDOM.render(<GettingAttributes />, document.querySelector("#app"))
You may also solve this by adding the click handler to the <p>
element: 您也可以通过将点击处理程序添加到
<p>
元素来解决此问题:
<div >
<p id="foo" onClick={this.bar}>{this.state.value}</p>
</div>
Using e.currentTarget.id
will quickly solve your problem, just know what the currentTarget
stands for instead of Target
alone. 使用
e.currentTarget.id
可以快速解决您的问题,只需知道currentTarget
代表什么而不是Target
。 Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.