far*_*raz 5 javascript reactjs
通过回调函数将数据从子组件传递到父组件但不知何故它不起作用.我在这做错了什么?将数据从子组件传递到父组件 - 通过回调函数进行响应
https://codepen.io/silentarrowz/pen/GEMQEP?editors=0010
这是代码
class App extends React.Component{
constructor(props){
super(props);
this.state={
input:'this is the input for now'
}
//this.handleInput=this.handleInput.bind(this);
}
handleInput(x){
this.setState({
input:x
});
alert(this.state.input);
}
render(){
return(
<div>
<h1>Passing props from Child to Parent Component</h1>
<Child getInput={this.handleInput} />
here's the input: {this.state.input}
</div>
);
}
}
class Child extends React.Component{
constructor(){
super();
this.state={
text:''
}
}
passingProps(e){
var newInput=e.target.value;
//alert(newInput);
this.setState({
text:newInput
});
this.props.getInput(this.state.text);
}
render(){
return(
<div>
<input type="text" placeholder="please input a name..." onChange={this.passingProps} />
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)
有几个问题。
1)你必须绑定 passingProps
constructor(){
super();
this.state={
text:''
}
this.passingProps = this.passingProps.bind(this);
}
Run Code Online (Sandbox Code Playgroud)
2)this.setState是异步的,因此不能保证this.state.text在您将其传递给this.props.getInput. 你可以这样做
this.props.getInput(newInput)
Run Code Online (Sandbox Code Playgroud)
或者
this.setState({ text: newInput }, () => {
this.props.getInput(this.state.text);
})
Run Code Online (Sandbox Code Playgroud)
来解决这个问题。
| 归档时间: |
|
| 查看次数: |
6866 次 |
| 最近记录: |