我正在开发我的第一个小型游戏应用程序。
我想要做的是将布尔GreenF传递给Green组件。 (此组件是一个绿色按钮,用于检查greenFlash是否为true,然后更改按钮的颜色-正常)。
但是greenF状态不会从false更改为true,因此Green组件不会更改。我需要在play()函数中随时更改GreenF;
现在,无论何时将greenF传递给greenF,它都未定义。我不确定我是否缺少某些东西或在理解React状态时遇到问题。
这只是我代码的开始,所以没有什么比这更完整的了,只是为了您的理解。
import React, {Component} from 'react';
import {StyleSheet, Text, View,TouchableOpacity, Button} from 'react-native';
import Green from './components/Green.js'
export default class App extends Component{
constructor (props){
super(props);
this.state = {
greenF: false
}
}
render() {
let score; // user score
let seq=[];//order of playing colors
let playerSeq=[]; //order of user pressing the colors
let round; // round number
let ok; //does the user pressed right
let win;
let compTurn;
let greenF;
/*
for (var i=0; i<5; i++) {
seq.push(Math.floor(Math.random()*4)+1);
}
*/
function play() {
seq=[1,2,3,1,4]; //just for test
compTurn=true;
round=1;
for (var i=0; i<round ; i++){
switch (i) {
case 1:
this.setState({ greenF: true })
break;
case 2:
//tbchanged
break;
case 3:
//tbchanged
break;
case 4:
//tbchanged
break;
}
compTurn=false;
}
}
return (
<View>
<Button
title='start'
color='black'
onPress={() => {
play();
}}>
</Button>
<Green greenFlash={greenF}> </Green> //GREENF IS UNDEFINED
</View>
);
}
}
答案 0 :(得分:3)
您必须从状态中取出它,否则它实际上是未定义的:
<Green greenFlash={this.state.greenF} />
从React docs:
除了获取输入数据(通过this.props访问)之外,组件还可以维护内部状态数据(通过this.state访问)。当组件的状态数据更改时,将通过重新调用render()来更新渲染的标记。
话虽这么说,但play()方法和您要更改的静态变量实际上是错误地使用/定义的。您要做的就是始终使用状态来触发组件的重新渲染:
export default class App extends Component{
constructor (props){
super(props);
this.state = {
greenF: false,
score: 0,
seq: [1,2,3,1,4],
playerSeq: [],
round: 1,
}
}
play()
{
// I don't know exactly what you want to achieve here, but the idea
// was to move the play method outside the render method
seq=[1,2,3,1,4]; //just for test
compTurn=true;
round=1;
for (var i=0; i<round ; i++){
switch (i) {
case 1:
this.setState({ greenF: true })
break;
case 2:
//tbchanged
break;
case 3:
//tbchanged
break;
case 4:
//tbchanged
break;
}
compTurn=false;
}
}
render()
{
return (
<View>
<Button
title='start'
color='black'
onPress={this.play}>
</Button>
<Green greenFlash={this.state.greenF}> </Green>
</View>
);
}
}