javascript - 如何在 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 1
或Text 2
,然后我将获得event
内部toggle
功能。接下来我将单击按钮Red
或Blue
。然后我想将类更改为我之前点击过的那个red-color
或blue-color
那个。Text
如何在父组件中获取事件以找到特定的事件,text
或者有任何其他方法可以解决这个问题?
我想获取event.target
Parent 组件的内部。我event
在父对象中得到了对象,event.target
但是null
解决方案
<div>
<EditComponent changeColor={this.changeColor.bind(this)}>
<TextComonent toggle={this.toggle}>
</div>
尝试这种方式不要在父组件中绑定函数并尝试,你会得到目标
推荐阅读
- reactjs - 模态不使用 React 路由器和链接关闭
- css - 具有特定属性的后代元素的 css 选择器。
- objective-c - macOS 获取系统中创建连接的通知
- url - PHP中的GET url数据限制
- azure - 如何在 Sprint 中添加任务、问题和错误
- java - 在 Android Studio 中隐藏私人信息的最佳方法是什么?
- c++ - 如何使用 CMake 为其他项目“安装”和使用内部依赖项
- pandas - 相同的 Pandas 数据框大小不同
- chart.js - 如何在 Chart.JS 中添加文本框
- java - 带有 JPA 事务的 JAX-WS Web 服务