所以我试图在react中检索div属性中的数据。 JSFiddle 显示了我遇到的问题。事件触发后 this.state.value 设置为空字符串。
在阅读 another stack overflow post 后,我开始使用 div 的 data-* 属性,但我不能使用 jQuery,所以我改用 id。有什么想法吗?
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>
);
}
}
最佳答案
使用
e.currentTarget.id
而不是
e.target.id
.currentTarget 将定位实际包含事件监听器的元素。在您的场景中,.target 是其中包含文本的 p 标记,它没有在您的状态中设置的 id。
关于javascript - 在 React.js 中从 div 获取 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50956462/