【问题标题】:How to pass tag id to to onClick function in react?如何在反应中将标签 ID 传递给 onClick 函数?
【发布时间】:2017-11-08 11:04:02
【问题描述】:

我想将标签 <th id='1' onClick={this.click.bind(this)}> 的 id 传递给点击功能。假设我想在click() 函数console.log 中打印<th> 的ID。 这是代码-

<thead>
 <tr>
    <th id='name' onClick={this.click.bind(this)}>Name</th>
    <th id='phone' onClick={this.click.bind(this)}>Phone number</th>
    <th id='email' onClick={this.click.bind(this)}>Email</th>
 </tr>
</thead>

click() 函数-

click(){
console.log('the clicked id is:') //here i want the id
}

【问题讨论】:

标签: reactjs


【解决方案1】:

Bind 接受参数

this.click.bind(this, 'phone')

click(phone) {
  // ...
}

或使用 es6 箭头函数

onClick={() => this.click('phone')}

【讨论】:

    【解决方案2】:

    你可以这样做:

    const headers = [
      { id: 'name', label: 'Name' },
      { id: 'phone', label: 'Phone' },
      { id: 'Email', label: 'Name' },
    ]
    
    const ab = (
      <thead>
        <tr>
          {headers.map(doc => (
            <th onClick={() => { this.click(doc.id) }}>{doc.label}</th>
          ))}
        </tr>
      </thead>
    )
    

    【讨论】:

      【解决方案3】:

      这应该可行:

      <tr>
        <th id='name' onClick={this.foo}>Name</th>
        <th id='phone' onClick={this.foo}>Phone number</th>
        <th id='email' onClick={this.foo}>Email</th>
      </tr>
      

      点击功能

         foo=(e)=> {
           console.log(e.target.id);
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-23
        • 2016-07-29
        • 1970-01-01
        • 2020-07-23
        • 1970-01-01
        • 1970-01-01
        • 2021-04-08
        • 2020-10-23
        相关资源
        最近更新 更多