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);
}
// ...
}
添加回答
舉報