用动态参数绑定方法

时间:2018-07-13 08:56:23

标签: javascript reactjs

出于性能原因,我想将clickHandler绑定到构造函数中,并希望在render()时将索引传递给Click Handler。

constructor(){
  this.clickHandler = this.clickHandler.bind(this);
}

render(){
  array.map(item,index)=>{
     <input onclick={this.clickHandler} />   //Here i want to pass the item & index as args
  }
}

有建议吗?

4 个答案:

答案 0 :(得分:2)

创建一个处理程序,然后在onClick prop上调用它,然后从那里传递索引。

示例

// Creates and returns a function to be called with click event
clickHandler = index => event => {
  console.log(index)
}

<input onClick={this.clickHander(index)} />

clickHandler = (index, event) => {
 // handle here
}

<input onClick={() => this.clickHander(index, event)} />

如果使用的是ES5,请使用常规功能

答案 1 :(得分:1)

围绕它创建一个匿名函数,这样您就可以将参数传递给函数

8
7
6
5
4
3
2
1
0
0
1
2
3
4
5
6
7
8
9

如果您的编译器不支持粗箭头语法,则可以

     <input onclick={() => this.clickHandler(item,index)} />   

答案 2 :(得分:1)

您可能会使用一种咖喱函数:

    constructor(){
      this.clickHandler = this.clickHandler.bind(this);
    }

    clickHandler(index) {
        return function(e) {
          // do click things
        }.bind(this);
    }

    render(){
      array.map(item,index)=>{
         <input onclick={this.clickHandler(index)} />   //Here i want to pass the item & index as args
      }
}

您真的不能避免为每个index创建一个新的函数回调。

答案 3 :(得分:0)

尝试一下。 :)

"geometry": {
    "type": "Point",
    "coordinates": [
        52.5219000000000022509993868879973888397216796875,                        
        13.413199999999999789679350215010344982147216796875
    ]
}