我试图通过子组件的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功能表现不正常。任何有关如何更新父状态然后更新子状态的帮助将深表感谢。提前谢谢!
答案 0 :(得分:0)
将要更新的值传递给子项
if($a) {
return response()->json([
'location' => realpath($a)
]);
}
然后使用props
在child中提取此值 孩子的 <TicTacToeBox key = {Math.random(10000)} callback={this.nextOneCallback} nextOne={this.state.nextOne}/>);
因此,无论何时您从子节点点击回调函数,该值都将在父节点和子节点中更新。