![](/img/trans.png)
[英]React Passing Data From Child Component to Parent Component via a onClick
[英]passing data from child to parent component - react - via callback function
通過回調函數將數據從子級傳遞到父級組件,但是不起作用。 我在這里做錯了什么? 將數據從子級傳遞到父級組件-反應-通過回調函數
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')
);
有幾個問題。
1)您必須綁定passingProps
constructor(){
super();
this.state={
text:''
}
this.passingProps = this.passingProps.bind(this);
}
2) this.setState
是異步的,所以它不能保證this.state.text
將被設置為你想要的,你把它傳遞給時間值this.props.getInput
。 你可以做
this.props.getInput(newInput)
要么
this.setState({ text: newInput }, () => {
this.props.getInput(this.state.text);
})
解決該問題。
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')
);
這是您問題的答案。 希望你的難題解決。
this
不會自動綁定到您的passingProps函數中。 嘗試使用箭頭函數語法將其綁定。
passingProps = e => {
var newInput=e.target.value;
//alert(newInput);
this.setState({
text:newInput
});
this.props.getInput(this.state.text);
}
在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函數中發生了相同的事情。
您需要糾正兩件事:
this.setState({input: 'xxx'})
之后使用this.state.input
。 這就是為什么不這樣做的原因。 this.passingProps = this.passingProps.bind(this)
被定義什么this
是目前的范圍。 當你使用this
在組件的功能, this
需要被約束。 更改了密碼筆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.