繁体   English   中英

通过回调更新父组件状态后,无法更新子组件状态

[英]Unable to update child component state after updating parent component state through callback

我正在尝试通过子组件的onPress函数中的回调来更新父组件的状态,然后更新子组件本身的状态。 但是,我只能更新父组件或子组件的状态,而不能同时更新两个组件的状态。 有关我的问题的代码如下:

 export default class GameScreen extends React.Component { constructor (props) { super(props); this.state = { nextOne: 'X' } this.nextOneCallback = this.nextOneCallback.bind(this); } nextOneCallback () { this.setState({ nextOne: 'Y' }); } render() { const ticTacToeSquare = []; for (let i = 0; i < 3; i++) { const rowArray = []; for (let j = 0; j < 3; j++) { const newBox = (<TicTacToeBox key = {Math.random(10000)} callback={this.nextOneCallback}/>); rowArray.push(newBox); } const eachRenderedRow = ( <View key = {Math.random(10000)} style={{flexDirection: 'row'}}> {rowArray} </View> ); ticTacToeSquare.push(eachRenderedRow); } return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> {ticTacToeSquare} <Button title="Home" onPress={() => this.props.navigation.navigate('Home')} /> </View> ); } } class TicTacToeBox extends React.Component{ constructor(props) { super(props); this.state = { text: '', } } render () { return ( <View style={{ borderColor: 'black', borderWidth: 2, alignItems: 'center', justifyContent: 'center'}} > <Text style={{textAlign: 'center', height: 40, width: 40}} maxLength={1} onPress={ () => { this.setState((prevState, props) => ({text: 'X'})); // this.props.callback(); } }> {this.state.text} </Text> </View> ); } } 

TicTacToeBox的onPress函数的行为不符合预期。 对于如何更新父状态然后子状态的任何帮助,将深表感谢。 提前致谢!

也将您要更新的值传递给子级

<TicTacToeBox key = {Math.random(10000)} callback={this.nextOneCallback}  nextOne={this.state.nextOne}/>);

然后使用道具在孩子中提取该值

this.props.nextOne中的this.props.nextOne

因此,每当您从子项中调用回调函数时,父项和子项中的值都会得到更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM