[英]Why isn't my state updating?
我正在開發一個React組件,我不確定為什么我無法將更新功能發送到小部件並使其正確實現。 我以為綁定有錯誤,有人看到過這樣的東西嗎?
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component{
constructor(){
super();
this.state = {
txt: 'this is the state text',
cat: 0
}
}
update(e){
this.setState({txt: e.target.value})
}
render(){
let txt = this.props.txt
return (
<div>
<Widget txt={this.state.txt} update={this.update} />
</div>
)
}
}
class Widget extends React.Component{
render(){
return (
<div>
<input type="text"
// this is the error
onChange={this.props.update.bind(this) } />
<h1>{this.props.txt}</h1>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('app')
);
您要將方法綁定到父組件。
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component{
constructor(){
super();
this.state = {
txt: 'this is the state text',
cat: 0
}
}
update(e){
this.setState({txt: e.target.value})
}
render(){
let txt = this.state.txt;
return (
<div>
<Widget txt={this.state.txt} update={this.update.bind(this)} />
</div>
)
}
}
class Widget extends React.Component{
render(){
return (
<div>
<input type="text"
// this is the error
onChange={this.props.update} />
<h1>{this.props.txt}</h1>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('app')
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.