首页 > 解决方案 > 多重绑定 this(缩短代码)

问题描述

在构造函数中绑定 this 的多个 >4(大约 10 个)函数。有没有办法缩短代码?

constructor(props: SignupProps) {
    super(props);
    this._setDirty = this._setDirty.bind(this);
    this._handleUserInput = this._handleUserInput.bind(this);
    this._A = this._A.bind(this);
    this._B = this._B.bind(this);
}

我尝试了以下但不能。

 [this._setDirty, _this.handleUserInput, this._A, this._B].bind(this);

标签: reactjsecmascript-6thisbind

解决方案


您需要对方法进行循环并在.bind每次迭代时调用以使您的方法有效。例如:

const methods = ['_setDirty', '_a', '_b', ...];
methods.forEach(method => this[method] = this[method].bind(this));

推荐阅读