.Reactjs中的this引用错误

.this reference error in Reactjs

在我的 React 应用程序中,我有类似 below.the 的代码,发生的错误是 undefined removeOperation。当我在线检查时,错误是因为 this . 函数参考和解决方案是使用 .bind(this).Plz 有人帮助我在哪里我可以使用这个绑定,我已经尝试了很多方法 everthing leads错误

   fields = this.state.operations.map(function(operation,index){
          if(operation == "adjust-price-multiply"){
                return (<PriceMultiply key={index} removeOperation={this.removeOperation} />);
          }else if(operation == "adjust-price-add"){
                 return (<PriceAdd key={index} removeOperation={this.removeOperation} />);
          }else if(operation == "filter-products-includes"){
                  return (<IncludeProducts key={index} removeOperation={this.removeOperation} />);
          }else if(operation == "filter-products-excludes"){
                  return (<ExcludeProducts key={index} removeOperation={this.removeOperation} />);
          }
    });

您可以这样做:

fields = this.state.operations.map(function(operation,index){
      if(operation == "adjust-price-multiply"){
            return (<PriceMultiply key={index} removeOperation={this.removeOperation} />);
      }else if(operation == "adjust-price-add"){
             return (<PriceAdd key={index} removeOperation={this.removeOperation} />);
      }else if(operation == "filter-products-includes"){
              return (<IncludeProducts key={index} removeOperation={this.removeOperation} />);
      }else if(operation == "filter-products-excludes"){
              return (<ExcludeProducts key={index} removeOperation={this.removeOperation} />);
      }
}.bind(this));

或者,如果您正在使用某种 ES6 转译 (babel),this 在使用 ES6 箭头函数语法时会自动绑定(()=>{} 而不是 function() {}):

fields = this.state.operations.map((operation,index) => {
      if(operation == "adjust-price-multiply"){
            return (<PriceMultiply key={index} removeOperation={this.removeOperation} />);
      }else if(operation == "adjust-price-add"){
             return (<PriceAdd key={index} removeOperation={this.removeOperation} />);
      }else if(operation == "filter-products-includes"){
              return (<IncludeProducts key={index} removeOperation={this.removeOperation} />);
      }else if(operation == "filter-products-excludes"){
              return (<ExcludeProducts key={index} removeOperation={this.removeOperation} />);
      }
});