通过回调函数将数据从子组件传递到父组件 但不知怎的,它不起作用。 我在这做错了什么? 将数据从子组件传递到父组件 - 反应 - 通过回调函数
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')
);
答案 0 :(得分:3)
有几个问题。
1)你必须绑定constructor(){
super();
this.state={
text:''
}
this.passingProps = this.passingProps.bind(this);
}
this.setState
2)this.state.text
是异步的,因此无法保证将this.props.getInput
设置为您将其传递给this.props.getInput(newInput)
时所需的值。你可以做到
this.setState({ text: newInput }, () => {
this.props.getInput(this.state.text);
})
或
FileOutputStream
解决该问题。
答案 1 :(得分:1)
this
不会自动绑定在passingProps函数中。尝试使用箭头函数语法来绑定它。
passingProps = e => {
var newInput=e.target.value;
//alert(newInput);
this.setState({
text:newInput
});
this.props.getInput(this.state.text);
}
答案 2 :(得分:1)
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(event){
let value = event.target.value;
this.setState({
input:value
});
}
render(){
return(
<div>
<h1>{this.state.input}</h1>
<Child getInput={this.handleInput} />
</div>
);
}
}
class Child extends React.Component{
constructor(){
super(props);
}
render(){
return(
<div>
<input type="text" placeholder="please input a name..." onChange={this.props.getInput} />
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('app')
);
以下是您的问题的答案。我希望你的问题得到解决。
答案 3 :(得分:1)
在Child
组件中,您编写了以下代码:
passingProps(e){
var newInput=e.target.value;
//alert(newInput);
this.setState({
text:newInput
});
this.props.getInput(this.state.text);
}
问题是由于setState函数的异步行为造成的。这意味着你不能在一行上调用setState并期望在下一行更新它。 使用setState的回调函数来调用父组件的功能,如下所示:
passingProps(e){
var newInput=e.target.value;
//alert(newInput);
this.setState({ text: newInput }, () => {
this.props.getInput(this.state.text);
})
}
App组件的 handleInput 功能也发生了同样的事情。
答案 4 :(得分:1)
你需要纠正它的两件事:
this.state.input
this.setState({input: 'xxx'})
。 Here is reason why not it. this.passingProps = this.passingProps.bind(this)
定义了this
当前范围。当您在组件的功能中使用this
时,this
需要绑定。更改了codepen
答案 5 :(得分:0)