Javascript 将单击绑定到div并在React中获取属性数据

Javascript 将单击绑定到div并在React中获取属性数据,javascript,reactjs,Javascript,Reactjs,一页上有多个div。我想做的是在单击div时获取一个属性。在jquery中非常简单,但我使用的是Reactjs。这是我的密码。它可以工作,但每次我单击中最后一个元素的div属性时,它都会返回。以下是我的代码和代码笔URL。 类内容扩展了React.Component{ 建造师(道具){ 超级(道具) this.click=this.click.bind(this) } 单击(){ //this.prop.setActiveMenu(); var summary=this.refs.summar

一页上有多个div。我想做的是在单击div时获取一个属性。在jquery中非常简单,但我使用的是Reactjs。这是我的密码。它可以工作,但每次我单击中最后一个元素的div属性时,它都会返回。以下是我的代码和代码笔URL。

类内容扩展了React.Component{
建造师(道具){
超级(道具)
this.click=this.click.bind(this)
}
单击(){
//this.prop.setActiveMenu();
var summary=this.refs.summary;
console.log(summary.getAttribute('data-slug'))
}
render(){
返回(
{posts.map((post)=>{
返回(
{post.title}
{post.content}







); })} ); } }
我不鼓励您使用这种方法,您可以使用组件

ref prop接受一个函数并返回ref,因此传递一个字符串不起作用

class Content extends React.Component{
  constructor(props) {
    super(props)
    this.click = this.click.bind(this)
  }
  click(){
    console.log(this.summary.getAttribute('data-slug'))
  }

    render(){
        return(
          <div className="content">
            {posts.map((post)=>{
                return (
                    <div ref={ref => this.summary = ref} data-slug={post.slug} onClick={this.click} key={post.slug}>
                        <h1>{post.title}</h1>
                        <div>{post.content}</div>
                        <br/><br/><br/><br/><br/>
                    </div>
                );
            })}
          </div>
        );
    }
}
类内容扩展了React.Component{
建造师(道具){
超级(道具)
this.click=this.click.bind(this)
}
单击(){
console.log(this.summary.getAttribute('data-slug'))
}
render(){
返回(
{posts.map((post)=>{
返回(
this.summary=ref}data slug={post.slug}onClick={this.click}key={post.slug}>
{post.title}
{post.content}







); })} ); } }
这是因为每次迭代posts数组时都要更改映射中的ref元素。 这里不需要裁判

为什么不使用click事件中的event.target

onClick(event){
   console.log(event.target.getAttribute('data-slug'))
}
顺便说一句: 字符串引用被认为是遗留的。请看这里:

react的最新版本不推荐使用Ref字符串。我认为ref名称必须是唯一的,因此会覆盖所有以前的ref。您需要使用模板中的索引分配它,使用ref回调函数,使用事件道具将其提取到组件,或者只使用简单的click事件并从目标中提取值。
onClick(event){
   console.log(event.target.getAttribute('data-slug'))
}