我正在开发一个 React 组件,我不确定为什么我无法将更新函数发送到小部件并使其正确实现。我想错误出在绑定(bind)上,有人见过这样的事情吗?
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')
);
最佳答案
您想要将该方法绑定(bind)到父组件。
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')
);
关于javascript - 为什么我的状态没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34716581/