javascript - 避免 React 中的内联函数 : How to bind functions with arguments?

标签 javascript reactjs ecmascript-6 bind

我正在尝试关注 no-bind React 使用他们推荐的 ES6 类模式的规则:

class Foo extends React.Component {
  constructor() {
    super();
    this._onClick = this._onClick.bind(this);
  }
  render() {
    return (
      <div onClick={this._onClick}>
        Hello!
      </div>
    );
  }
  _onClick() {
    // Do whatever you like, referencing "this" as appropriate
  }
}

但是,当我需要将参数传递给 _onClick 时,需要更改什么?

我试过类似的方法:

import {someFunc} from 'some/path';

class Foo extends React.Component {
  constructor() {
    super();
    this._onClick = this._onClick.bind(this, a, b);
  }
  render() {
    const {
     prop1,
     prop2
    } = this.props;

    return (
      <div onClick={this._onClick(prop1, prop2}>
        Hello!
      </div>
    );
  }
  _onClick = (a, b) => {
    someFunc(a, b);
  }
}

但是,这不起作用。需要更改什么?

最佳答案

在构造函数中调用 bind 应该只将 this 作为单个参数传递。

this._onClick = this._onClick.bind(this);

在这里,您正在用具有正确 this 绑定(bind)的新属性覆盖属性 this._onClick。如果您的函数有两个参数,那么您应该在调用时正常传递它们。

将附加参数传递给 bind 意味着返回的函数已经提供了这些参数 - 在您的尝试中,_onClick 函数将始终具有其前两个参数 undefined ,因为 ab 在构造函数中没有值。

现在您已经将 this 绑定(bind)到您的函数,您可以从那里访问 this.props,而不必传递参数:

import {someFunc} from 'some/path';

class Foo extends React.Component {
  constructor() {
    super();
    this._onClick = this._onClick.bind(this);
  }
  render() {
    return (
      <div onClick={this._onClick}>
        Hello!
      </div>
    );
  }
  _onClick() {
    const {
     prop1,
     prop2
    } = this.props;
    someFunc(prop1, prop2);
  }
}

关于javascript - 避免 React 中的内联函数 : How to bind functions with arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231678/

相关文章:

javascript - 状态不更新

javascript - 从箭头函数返回对象

c# - AJAX + ASP.net 从 Sql Server 检索数据?

javascript - 在reactjs中控制导航栏中的redux属性

python - 帖子请求中禁止 (403) - django rest-react

javascript - 不嵌套地链接 ES6 Promise

Javascript 排序项目排除某些特定项目

javascript - React 中如何区分不同的表单输入?

javascript - 具有相同选项的多个下拉菜单 : how to remove currently selected item of one dropdown from other dropdowns?

javascript - Bootstrap 模式数据远程在 Chrome 中不起作用