使用参数绑定点击处理程序的“React - ES6 方式”

IT技术 javascript reactjs ecmascript-6
2021-05-04 19:07:59

我读了一堆关于冠词() => {}语法,在构造函数结合,在props等结合。但是从我的理解,结合this是昂贵的性能代价,做自动带箭头的功能结合是昂贵的,因为它每次都会创建一个新的匿名函数。

那么处理这个问题的最高效的“react方式”是什么?

构造函数中的绑定似乎适用于不需要传递参数的函数,如下所示:

constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
}

但是我们如何处理传递参数的绑定函数,而不是在 prop 中绑定它,像这样:

<li onClick={this.handleClick.bind(this, item.id)} />{item.name}</li>

是否结合this的构造函数,然后结合nullundefined在绑定功能,只有结合曾经在props结果?

请随时纠正我的任何误解。似乎这个问题的解决方案应该更广为人知和普遍......如果我不只是生活在岩石下!

编辑:

即使有抽象,点击处理程序也不会与每个单独的项目渲染绑定吗?

这里的文章中,他们给出了这个例子来避免绑定点击处理程序,但是因为 React.createClass 会自动绑定方法,我看不出这实际上是如何在每个项目渲染上绑定的?

var List = React.createClass({
  render() {
    let { handleClick } = this.props;
    // handleClick still expects an id, but we don't need to worry
    // about that here. Just pass the function itself and ListItem
    // will call it with the id.
    return (
      <ul>
        {this.props.items.map(item =>
          <ListItem key={item.id} item={item} onItemClick={handleClick} />
        )}
      </ul>
    );
  }
});

var ListItem = React.createClass({
  render() {
    // Don't need a bind here, since it's just calling
    // our own click handler
    return (
      <li onClick={this.handleClick}>
        {this.props.item.name}
      </li>
    );
  },

  handleClick() {
    // Our click handler knows the item's id, so it
    // can just pass it along.
    this.props.onItemClick(this.props.item.id);
  }
});

有人可以解释一下吗?这不是看起来像它避免了绑定每个 ListItem 渲染,但由于 React.createClass 中的自动绑定,它仍然可以吗?

我用class List extends Component语法而不是 createClass尝试了这个例子this.handleClick但没有定义,因为 handleClick 方法没有绑定到类。

归根结底,这似乎只是清理了冗长,实际上并没有通过减少方法绑定来提高性能......

4个回答

为您 <li onClick={this.handleClick.bind(this, item.id)} />{item.name}</li>

这通常意味着您需要另一个抽象层,即返回相同元素的新react组件,但您可以将 onClick 作为props以及项目 ID 作为props传递。然后在该组件中,您将调用this.props.onClick(this.props.id)或格式化数据。

本文列出了绑定实例方法的每种方式之间的所有差异以及每种方式如何影响性能https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56# .

如果传递参数,则必须绑定在render函数中,而不是在构造函数中。这可以使用绑定或箭头函数来完成。

<li onClick={this.handleClick.bind(this, item.id)} />{item.name}</li>

或者

<li onClick={() => this.handleClick(item.id)} />{item.name}</li>

这行得通吗?(使用typescript)

<Input type="password" onChange={this.onPasswordInputChange('primary')} />;
<Input type="password" onChange={this.onPasswordInputChange('secondary')} />;


interface IOnPasswordInputChange {
  (value: string): void;
}

private onPasswordInputChange = (type: string): IOnPasswordInputChange => {
  return (value: string) => {
    this.setState({ [type]: value });
  };
}
onDelete(e) {
    const id = e.target.dataset.id;
}

<DropdownItem data-id={item.id} onClick={this.onDelete}><i className="fa fa-trash" /> Remove</DropdownItem>