获取 ID 的 div 在 React.js

所以我试图在属性中获取数据 div 在 react. JSFiddle 显示了我遇到的问题。 this.state.value 触发事件后安装在空字符串中。

我开始使用属性 data-* 为了 div 看完之后
https://coderoad.ru/5309926/
stack overflow, 但我不能使用 jQuery, 所以我切换到了 id. 有任何想法吗?

https://jsfiddle.net/boloneyshinobi/yw6db9ts/1/

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

, 和
data-*

. 但优选的方法是
data-*

属性。

敬请期待
https://jsfiddle.net/yw6db9ts/41/
关联 JSFiddle 您的决定。

你必须安装 ref 在您要从中提取数据的项目上,然后您可以将数据安装到状态。 代码 IN 如果你替换
onClick={this.bar}


onClick={this.barById}

, 代码将从中提取数据
id

, 在第一种情况下,它将从属性中提取数据
data-*

.

快网

赞同来自:

原因 , 您不能选择属性
id

, 在于当前的事实
e.target

他是一个附属元素
<div>

, 这是
<p>

. 这是建议的解决方案:


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></gettingattributes>, document.querySelector/"#app"//


您还可以通过添加单击处理程序来解决此问题。
<p>

:


<div>
<p id="foo" onclick="{this.bar}">{this.state.value}</p>
</div>


使用
e.currentTarget.id

快速解决您的问题,只知道什么是什么意思
currentTarget

, 不仅
Target

. 祝你好运!
</p></p></div>

要回复问题请先登录注册