映射时将 props 参数传递给 React.js 中的函数

Pass props parameter to function in React.js when mapping

当我在组件渲染方法中通过 props 进行映射时,我可以将 prop 值传递给函数吗?我忘记了正确的方法来做到这一点。例如,我有一个类别标签控件,它只列出了一些带有名称的类别,但是 onClick 我想为单个类别执行一些功能。

var React = require("react");

var CategoryTags = React.createClass({

  propTypes: {
    categories: React.PropTypes.array.isRequired
  },

  render: function() {

      var categoryRows = this.props.categories.map(function (c, i) {

        return (
            <button onClick={ this.linkToCategory.bind(name) } >
              {c.name}
            </button>
        );

      }.bind(this));

    return (
        <span>{categoryRows}</span>
    );

  },

  linkToCategory: function (c) {
    console.log(c);
  }

});

所以在这个例子中,在通过类别进行映射时,我想传入单个类别的名称,以便我可以解析 link。当然,对象具有 link 属性 是有意义的,但在这种情况下没有。

传递给组件道具的类别对象示例

categories = [{'name': 'cat1'}, {'name': 'cat2'}];

.map 中绑定一个函数不是一个好主意,因为你总是要将一个新函数传递给组件,即使其他 prop 没有改变。这意味着它将始终被重新渲染,即使它不是必须的。

但是无论如何,你的代码的问题在于

  1. 没有变量name
  2. 您使用 .bind 不正确。

调用应该是

this.linkToCategory.bind(this, c.name)

传递给绑定 .bind 的第一个参数是 this 的值,而不是第一个参数(您 应该 知道,因为您正在使用 .bind(this)

您可以在 MDN documentation 中了解有关 .bind 的更多信息。

您还可以 return 来自事件处理程序的函数:

var CategoryTags = React.createClass({

  propTypes: {
    categories: React.PropTypes.array.isRequired
  },

  render: function() {

      var categoryRows = this.props.categories.map(function (c, i) {

        return (
            <button onClick={this.linkToCategory(c)} >
              {c.name}
            </button>
        );

      }.bind(this));

    return (
        <span>{categoryRows}</span>
    );

  },

  linkToCategory: function (c) {
      return () => {
          console.log(c);
      }
  }

});