首页 > 解决方案 > 获取响应组件的名称 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 使其突出显示。

标签: reactjs

解决方案


好吧,我告诉你答案。即使这是重复的,我也会告诉你答案是什么。

简短的回答

是的……但是很复杂。

长答案

让我们从这个简单的类开始:

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} />并不存在。有一些方法可以做到这一点,但它们仍然很复杂。


推荐阅读