在React中使用map()传递附加参数

los*_*193 3 javascript parameters arguments prop reactjs

我目前正在映射这样一个道具:

  renderList(item) {
      return(
        </div>
          shows up
        </div>
    )
  }

  render() { 
    return(
        <div> 
          {this.props.items.map(this.renderList)}
        </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我有另一个我想通过的道具

this.props.completed
Run Code Online (Sandbox Code Playgroud)

我想做的简化版

  renderList(item, completed) {
      return(
        </div>
          shows up
        </div>
    )
  }

  render() { 
    return(
        <div> 
          {this.props.items.map(this.renderList(this.props.items, this.props.completed)}
        </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

是否可以通过此地图功能传递另一个道具?

rya*_*ffy 7

有(至少)3种方法可以解决这个问题.最简单的方法是绑定renderList到组件实例并this.props.completed在其中引用:

constructor (props) {
    super(props);
    // it's more efficient to bind your functions once in the constructor than
    // doing so on every render
    this.renderList = this.renderList.bind(this);
  }

  renderList(item) {
      const completed = this.props.completed;
      return(
        <div>
          shows up
        </div>
    )
  }

  render() { 
    return(
        <div> 
          {this.props.items.map(this.renderList)}
        </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用闭包将属性传递给函数:

  renderList(completed, item) {
      return(
        <div>
          shows up
        </div>
    )
  }

  render() { 
    const completed = this.props.completed;
    const renderList = this.renderList;
    return(
        <div> 
          {this.props.items.map(function (item) {
             return renderList(completed, item);
          })}
        </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

第三种选择是将属性绑定到map()回调.

  renderList(completed, item) {
      return(
        <div>
          shows up
        </div>
    )
  }

  render() {
    return(
        <div> 
          {this.props.items.map(this.renderList.bind(this, this.props.completed))}
        </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)