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

标签 javascript reactjs parameters arguments prop

我目前正在像这样映射一个 Prop :

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

  render() { 
    return(
        <div> 
          {this.props.items.map(this.renderList)}
        </div>
    );
  }
}

我还有一个 Prop 要传递

this.props.completed

我想做的事情的简化版本

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

  render() { 
    return(
        <div> 
          {this.props.items.map(this.renderList(this.props.items, this.props.completed)}
        </div>
    );
  }
}

是否可以通过此 map 功能传递另一个 Prop ?

最佳答案

(至少)有 3 种方法可以解决这个问题。最简单的方法是将 renderList 绑定(bind)到您的组件实例并在其中引用 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>
    );
  }

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

  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>
    );
  }

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

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

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

关于javascript - 在 React 中使用 map() 传递附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39186942/

相关文章:

javascript - 单击 DIV 时如何切换 UL 列表?

javascript - S3 Node.js SDK,LastModified 日期格式?

javascript - 在 Javascript 中为对象属性赋予随机属性值

javascript - AngularJS:如何生成动态 ng-model

javascript - 如何将这三个函数全部写在父组件中,而不是写在子组件中 - ReactJS

reactjs - 在 React 中,如何使用多个状态属性设置 img src?

javascript - 异步还原。错误 : modifiers may not emit actions

php - Alamofire swift : upload more than 10mb file?

Android:如何将参数传递给 AsyncTask 的 onPreExecute()?

grails,仅将当前 url 中的现有参数添加到分页