3 回答
TA贡献1869条经验 获得超4个赞
class SomeClass extends React.Component { handleInputChange = (val) => { console.log('selectionMade: ', val); }}
transform-class-properties
{ "plugins": [ "transform-class-properties" ]}
TA贡献1818条经验 获得超3个赞
.bind
class SomeClass extends React.Component { constructor() { super(); this.handleInputChange = (val) => { console.log('selectionMade: ', val, this); }; … }}
constructor()
.bind
class SomeClass extends React.Component { constructor() { super(); this.handleInputChange = this.handleInputChange.bind(this); … } handleInputChange(val) { console.log('selectionMade: ', val, this); }}
TA贡献1865条经验 获得超7个赞
我知道这个问题已经得到了充分的回答,但我有一点贡献要做(对于那些不想使用实验功能的人来说)。由于必须在构造函数中绑定多个函数绑定并使其看起来很混乱的问题,我想出了一个实用方法,一旦绑定并调用构造函数,就会自动为您完成所有必要的方法绑定。
假设我有这个类的构造函数:
//src/components/PetEditor.jsx
import React from 'react';
class PetEditor extends React.Component {
constructor(props){
super(props);
this.state = props.currentPet || {tags:[], photoUrls: []};
this.tagInput = null;
this.htmlNode = null;
this.removeTag = this.removeTag.bind(this);
this.handleChange = this.handleChange.bind(this);
this.modifyState = this.modifyState.bind(this);
this.handleKeyUp = this.handleKeyUp.bind(this);
this.addTag = this.addTag.bind(this);
this.removeTag = this.removeTag.bind(this);
this.savePet = this.savePet.bind(this);
this.addPhotoInput = this.addPhotoInput.bind(this);
this.handleSelect = this.handleSelect.bind(this);
}
// ... actual method declarations omitted
}
看起来很乱,不是吗?现在我创建了这个实用程序方法
//src/utils/index.js
/**
* NB: to use this method, you need to bind it to the object instance calling it
*/
export function bindMethodsToSelf(objClass, otherMethodsToIgnore=[]){
const self = this;
Object.getOwnPropertyNames(objClass.prototype)
.forEach(method => {
//skip constructor, render and any overrides of lifecycle methods
if(method.startsWith('component')
|| method==='constructor'
|| method==='render') return;
//any other methods you don't want bound to self
if(otherMethodsToIgnore.indexOf(method)>-1) return;
//bind all other methods to class instance
self[method] = self[method].bind(self);
});
}
现在我所需要做的就是导入该实用程序,并向构造函数添加一个调用,并且不再需要绑定构造函数中的每个新方法。新构造函数现在看起来很干净,如下所示:
//src/components/PetEditor.jsx
import React from 'react';
import { bindMethodsToSelf } from '../utils';
class PetEditor extends React.Component {
constructor(props){
super(props);
this.state = props.currentPet || {tags:[], photoUrls: []};
this.tagInput = null;
this.htmlNode = null;
bindMethodsToSelf.bind(this)(PetEditor);
}
// ...
}
添加回答
举报