[英]React bind in constructor, how to pass parameters to props
我試圖將我的React類轉換為ES6,但是我在這個過程中遇到了一些困難。我想在構造函數中創建綁定,而不是在渲染視圖中。
現在,如果我有一個帶有setState的根模塊,需要一個參數,例如:
constructor() {
super();
this.state = {
mood: ""
};
this.updateMood(value) = this.updateMood.bind(this,value);
}
updateMood(value) {
this.setState({mood: value});
}
然后我將此函數傳遞給組件:
<customElement updateMood={this.updateMood}></customElement>
然后在customElement模塊中,我有這樣的事情:
constructor() {
super();
}
update(e) {
this.props.updateMood(e.target.value);
}
在渲染中:
<input onChange={this.update} />
這是正確的方法嗎? 因為我不能讓它工作;-(
你不能使用this.updateMood(value) = this.updateMood.bind(this,value);
構造,因為它是語法錯誤。
你可以像這樣解決你的問題
class CustomElement extends React.Component {
constructor() {
super();
this.update = this.update.bind(this);
}
update(e) {
this.props.updateMood(e.target.value);
}
render() {
return <input onChange={this.update} />
}
}
class Parent extends React.Component {
constructor() {
super();
this.state = {
mood: ""
};
this.updateMood = this.updateMood.bind(this);
}
updateMood(value) {
this.setState({ mood: value });
}
render() {
return <div>
<CustomElement updateMood={this.updateMood}></CustomElement>
<h1>{ this.state.mood }</h1>
</div>
}
}
或者,根據您的babel設置或使用打字稿,以下內容實現相同,但編寫/維護更方便:
class Parent extends React.Component {
constructor() {
super();
this.state = {
mood: ""
};
}
updateMood = (value) => {
this.setState({ mood: value });
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.