在React中获取被点击元素的道具

Chr*_*ger 2 reactjs

目前正在学习React,需要获得clicked元素的支持。我设法得到了它,但感觉不像是“正确”的反应方式。

这是我所拥有的(有效):

filterProjects = (event) => {
  const value = event.currentTarget.getAttribute("filterTarget")
  console.log(value)
}
Run Code Online (Sandbox Code Playgroud)

最初,我尝试了多种方法,例如: const value = this.props.filterTargetconst value = event.currentTarget.this.props.filterTarget什至使用,refundefined在控制台记录该值时全部返回。

this.props因为它是类Component的一部分,所以使用)。

这是我的目标元素的样子:

const categories = data.allPrismicProjectCategory.edges.map((cat, index) => {
      return (
        <a
          key={index}
          onClick={this.filterProjects}
          filterTarget={cat.node.uid}
        >
          {cat.node.data.category.text}
        </a>
      )
    })
Run Code Online (Sandbox Code Playgroud)

rav*_*l91 5

一种简单的方法是传递值本身,

onClick={() => this.filterProjects(cat.node.uid)}
Run Code Online (Sandbox Code Playgroud)

还有功能

filterProjects = (value) => {
  console.log(value)
}
Run Code Online (Sandbox Code Playgroud)