>我正在尝试通过子组件的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
因此,每当您从子级点击回调函数时,该值都会在父级和子级中更新。