reactjs - 获取响应组件的名称 onClick
问题描述
我正在尝试获取被点击的反应组件的名称。
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
console.log("I WANTED TO PRINT 'MyComponent' HERE")
}
render() {
<MyComponent onClick={this.handleClick}>
}
我可以通过使用添加的道具来做到这一点,例如data-
orname=
但我想知道是否有一种MyComponent
无需多次输入的方法。
我想这样做的原因是我可以获得组件的名称,以便我可以更改 CSS 使其突出显示。
解决方案
好吧,我告诉你答案。即使这是重复的,我也会告诉你答案是什么。
简短的回答
是的……但是很复杂。
长答案
让我们从这个简单的类开始:
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
console.log("Component");
}
render(){
return (
<div>
<Component onClick={this.handleClick} />
</div>
)
}
然后呢?首先,您希望组件在handleClick()
函数中。就这么简单:
constructor(props){
super(props);
this.state = {
name: "Component"
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
// or whatever you want to do with it, just replace "Component" with this.state.name
console.log(this.state.name);
}
render(){
return (
<div>
<Component onClick={this.handleClick} />
</div>
)
}
所以我所做的是添加一个新的this.state.name
,然后在handleClick()
函数中使用它。这是一个很好的理由bind(this)
。所以之后bind(this)
,该功能将能够state
直接访问。如果要更改this.state.name
,请使用this.setState({name: /* whatever you want it to change to */ })
.
这比评论中指出的答案更有效,因为对于评论中指出的答案,如果您有多个<Component />
s,那么您将不得不使用“组件”超过 2 次。相反,使用此解决方案,您仍然只需要使用“组件”两次。
但是仍然几乎没有办法只使用 1 次“组件”。为什么?因为答案和更多答案都有 2 个或更多对“组件”的引用,因为无法将内部的标签名称直接连接return
到类的外部。你可能想要的,<{this.state.name} />
并不存在。有一些方法可以做到这一点,但它们仍然很复杂。
推荐阅读
- apache-kafka - 在 kafka 中哪里存储可重用数据?
- java - Flutter Insecure HTTP is not allowed by platform Error
- ios - 我怎样才能有一个“点击”到父视图的子视图
- wpf - Windows10 NT Shell ,使用 WPF Application 替换 Explorer.exe
- python - pandas - 删除 MultiIndex DataFrame 中的重复行
- node.js - ExpressJS: req.hostname 属性是否足以将其用作针对域白名单的安全性验证器?
- google-sheets - 将列转入行并添加计数
- jquery - JQuery Datatable 初始化两次
- ruby-on-rails - Ransack gem 不查询结果
- mongodb - Micronaut 在控制器中正确处理 io.reactivex.Maybe,但如何处理?