通过回调函数将数据从子级传递到父级组件,但是不起作用。我在这里做错了什么?将数据从子级传递到父级组件-反应-通过回调函数
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
passingProps
constructor(){ super(); this.state={ text:'' } this.passingProps = this.passingProps.bind(this); }
2)this.setState是异步的,因此不能保证this.state.text在传递给时将其设置为所需的值this.props.getInput。你可以做
this.setState
this.state.text
this.props.getInput
this.props.getInput(newInput)
要么
this.setState({ text: newInput }, () => { this.props.getInput(this.state.text); })
解决该问题。