javascript - 如何在Reactjs中有参数的构造函数中绑定(bind)函数

标签 javascript reactjs

这是我的功能:

remove(element)
{   
    this.setState({ search: this.state.search.filter( item => item !== element ) }); 
}  

我收到此错误:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). 
Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

如果我这样设置:

constructor()
{
    this.remove = this.remove.bind(this);
}
render() 
{   
    return (
        <div>
            { this.state.search.map( (item, index) =>  
                (   
                    <button key={index} onClick={this.remove(item)}>{item.search}: {item.text}</button>
                ))  
            }   
            </div>
        </div>
    );
}

但是如果我从构造函数中删除绑定(bind)(其实并不重要)并将按钮行更改为:

<button key={index} onClick={this.remove.bind(this, item)}>{item.search}: {item.text}</button>

所以我的问题是,有没有办法将它绑定(bind)在构造函数中,以便它可以接受参数?

最佳答案

this.remove(item)this.remove.bind(this, item) 之间的区别在于,第一个调用函数,而第二个创建一个新函数。

So my question is, is there a way to bind it in the constructor so that it can take on the parameter?

您可以使用this.remove.bind(this, item)执行构造函数的绑定(bind),尽管这是不必要的。

如果您想将 item 传递给事件处理程序,那么您必须.map 中创建一个可以访问item,使用您当前的设置。这可以通过 .bind 或通过闭包来完成。无论哪种情况,都不需要在构造函数中进行绑定(bind)。

如果以不同的方式提供item,您只能避免创建新函数,例如用另一个以 item 作为 prop 的组件包装按钮(因此将函数创建进一步向下推):

function Button({item, onClick}) {
  return <button onClick={() => onClick(item)}>{item.search}: {item.text}</button>;
}

class Component extends React.Component {
  constructor()
  {
      this.remove = this.remove.bind(this);
  }

  render() 
  {   
      return (
          <div>
              { this.state.search.map( (item, index) =>  
                  (   
                      <Button key={index} onClick={this.remove} item={item} />
                  ))  
              }   
              </div>
          </div>
      );
  }
}

关于javascript - 如何在Reactjs中有参数的构造函数中绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41453744/

相关文章:

javascript - CSS 模块被捆绑,但没有使用使用 Rollup underhood 的 TSDX 引用

reactjs - React/Typescript 属性 'ID' 在类型 'never' 上不存在 .ts(2339)

javascript - 如何清理模块中的导入语句

javascript - JQuery - 绑定(bind)/附加到 document.ready

javascript - 选项没有突出显示

javascript - 两个类之间的平滑动画(特别是字体系列标签)

javascript - 如何将客户端的图像插入到编辑器中?

javascript - 为什么我的 Suckerfish-as-tooltip 解决方案会逐渐缩进元素?

javascript - ReactJS 和 i18n.js : Translations with links

javascript - 在 React 中将 props 从 Parent 传递给 child 并使用 map 循环?