如何将标记id传递给onClick中的onClick函数?

问题描述 投票:-2回答:3

我想将标签<th id='1' onClick={this.click.bind(this)}>的id传递给click功能。假设我想在<th>函数console.log中打印click()的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
3个回答
0
投票

绑定需要参数

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

click(phone) {
  // ...
}

或使用es6箭头功能

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

0
投票

你可以这样做:

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>
)

0
投票

这应该工作:

<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>

onclick功能

   foo=(e)=> {
     console.log(e.target.id);
   }
© www.soinside.com 2019 - 2024. All rights reserved.