絕地?zé)o雙
2023-05-11 16:36:41
我對(duì) React Native 中的狀態(tài)概念還很陌生,無法使用它們來更改組件的狀態(tài)。我有三個(gè)文本組件,一個(gè)是問題,另外兩個(gè)是答案(是和否),另一個(gè)文本組件檢查我對(duì)問題的回答是否已寫,因此檢查文本組件。當(dāng)我針對(duì)某個(gè)問題單擊“是”時(shí),如果答案為“是”,則最后一個(gè)檢查組件的狀態(tài)應(yīng)更改為“正確”,如果答案為“否”,則更改為“錯(cuò)誤”。所以基本上,這就是我想要做的:這是我到目前為止所擁有的:這是我得到的錯(cuò)誤:這是我到目前為止的代碼: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} />}誰能告訴我怎么做?謝謝!
1 回答

汪汪一只貓
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
像這樣使用 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')
}
}
設(shè)置檢查按鈕 onPress={checkAnswer}
添加回答
舉報(bào)
0/150
提交
取消