首页 > 解决方案 > 如何在 ReactJS 中获取父组件内的事件目标

问题描述

我有一个带有代码的主要组件

changeColor = (color) => {

}

toggle = (e) => {
  console.log(e.target)
}

<div>
  <EditComponent changeColor={this.changeColor.bind(this)}>
  <TextComonent toggle={this.toggle.bind(this)}>
</div>

编辑组件

color = (value) => {
  this.props.changeColor(value)
}
<div>
  <button value='red' onClick={this.color.bind(this,"red")}>Red</button>
  <button value='blue' onClick={this.color.bind(this,"blue")}>Blue</button>
</div>

文本组件

toggle = (e) => {
  this.props.toggle(e)
}
<div>
  <p class="black-color" onClick={this.toggle.bind(this)}>Text 1</p>
  <p class="black-color" onClick={this.toggle.bind(this)}>Text 2</p>
</div>

我将先单击Text 1Text 2,然后我将获得event内部toggle功能。接下来我将单击按钮RedBlue。然后我想将类更改为我之前点击过的那个red-colorblue-color那个。Text如何在父组件中获取事件以找到特定的事件,text或者有任何其他方法可以解决这个问题?

我想获取event.targetParent 组件的内部。我event在父对象中得到了对象,event.target但是null

标签: javascriptreactjs

解决方案


<div>
 <EditComponent changeColor={this.changeColor.bind(this)}>
 <TextComonent toggle={this.toggle}>
 </div>

尝试这种方式不要在父组件中绑定函数并尝试,你会得到目标


推荐阅读