reactjs - 多重绑定 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);
解决方案
您需要对方法进行循环并在.bind
每次迭代时调用以使您的方法有效。例如:
const methods = ['_setDirty', '_a', '_b', ...];
methods.forEach(method => this[method] = this[method].bind(this));
推荐阅读
- javascript - 带有新元素的 Nodemailer
- ruby-on-rails - CounterCache 不适用于多态关联
- c++ - 如何使用线程类编译 cpp 文件?
- c++ - 展开可变参数模板结构
- angularjs - 具有不同保存选项的 Angular MaterialJS 对话框表单
- php - 如何在不使用 markdown 的情况下将纯文本版本添加到 Laravel 电子邮件
- smtp - Msmtprc SMTP 与 Office365
- python - pyswagger 中的解析错误:ValueError: Can't resolve type from:(String, )
- c - C中的指针及其值
- java - Java8使用方法参考按2个字段排序