我对响应本机中的状态这个概念很陌生,很难用它们来更改组件的状态。我有三个文本组件,一个是问题,另外两个是答案(是和否),另一个是检查我对问题的答案是否为写的文本组件,因此是检查文本组件。当我对某个问题单击“是”时,如果答案为“是”,则最后一个检查组件的状态应更改为“正确”,如果答案为否,则应更改为“错误”。所以基本上,这就是我想要做的:
这是我到目前为止所拥有的:
这是我得到的错误:
这是我到目前为止的代码:
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Alert, ScrollView, Image } from 'react-native';
// import TextComp from './components/Home2'
export default function App() {
const [answer, setAnswer] = useState('answer');
const [correctAns, setCorrectAns] = useState('');
const useEffect = () => {
if (answer == 'answer') {
setCorrectAns('please answer!');
} else if (answer == 'Yes') {
setCorrectAns('Right');
} else if (answer == 'No') {
setCorrectAns('Wrong');
};
};
const corAns = () => { Alert('Your answer was ', correctAns) }
return (
<ScrollView style={styles.container}>
<View style={{ alignItems: 'center' }}>
<Image source={require('./images/pic.jpeg')} style={styles.uriImg} />
<Text style={styles.title}>Is this Mt. Fuji?</Text>
<TouchableOpacity
onPress={() => setAnswer('Yes')}>
<Text style={styles.text}>Yes</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => setAnswer('No')}>
<Text style={styles.text}>No</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={corAns}>
<Text style={styles.text2}>Check</Text>
</TouchableOpacity>
<Image source={require('./images/yellow.png')} style={styles.uriImg} />
<Text style={styles.title}>Is this red color?</Text>
<TouchableOpacity
onPress={() => setAnswer('Yes')}>
<Text style={styles.text}>Yes</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => setAnswer('No')}>
<Text style={styles.text}>No</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={corAns}>
<Text style={styles.text2}>Check</Text>
</TouchableOpacity>
</View>
</ScrollView>);
}
谁能告诉我该怎么做?谢谢!
答案 0 :(得分:1)
像这样使用useEffect
useEffect(() => {
if (answer === 'Yes') {
Alert.alert('Right')
}
if (answer === 'No') {
Alert.alert('Wrong')
}
}, [ answer ])
或按检查按钮
const checkAnswer = () => {
if (answer === 'Yes') {
Alert.alert('Right')
}
if (answer === 'No') {
Alert.alert('Wrong')
}
if (answer === 'answer') {
Alert.alert('please answer')
}
}
设置检查按钮onPress = {checkAnswer}