我正在研究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')
);
答案 0 :(得分:1)
您希望将方法绑定到父组件。
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')
);