简体   繁体   English

React组件如何简化这个onClick函数?

[英]React component how to simplify this onClick function?

This is not really a React specific question, but I think it helps to know the context. 这不是React特定的问题,但我认为有助于了解上下文。 In a component I'm generating some table rows. 在一个组件中,我正在生成一些表行。 Each row needs an onClick function that passes an id to the components handleUnlink method. 每行都需要一个onClick函数,它将id传递给组件handleUnlink方法。

I got it to work with the code below, but it's making my head spin a bit and I have a feeling that this could be done in a simpeler way. 我得到它使用下面的代码,但它让我的头旋转了一点,我有一种感觉,这可以以一种简单的方式完成。 Am I right? 我对吗?

var fn = function(id){
  return function(){
    this.handleUnlink(id);
  }.bind(this);
}.bind(this); 

var linkedListHtml = this.state.linkedList.map( p => {
  return(
    <tr key={p.id}>
    <td>{p.name}</td>
    <td><mui.Icon icon='action-highlight-remove' onClick={fn(p.id)}/></td>
    </tr>);
});

Function.prototype.bind() also does partial application of any additional arguments, so you should be able to do this instead: Function.prototype.bind()也会对任何其他参数进行部分应用,因此您应该能够这样做:

onClick={this.handleUnlink.bind(this, p.id)}

Bonus: The this argument to bind() is redundant if you're using React.createClass() to create your component, as it auto-binds methods for you, so I usually end up writing a partial helper: 额外:如果你使用React.createClass()来创建你的组件,那么bind()this参数是多余的,因为它为你自动绑定方法,所以我通常最终编写一个partial帮助器:

'use strict';
var slice = Array.prototype.slice
function partial(fn) {
  var partialArgs = slice.call(arguments, 1)
  return function() {
    return fn.apply(this, partialArgs.concat(slice.call(arguments)))
  }
}
module.exports = partial

... ...

var partial = require('./utils/partial')
// ...
onClick={partial(this.handleUnlink, p.id)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM