无法让状态在 React Native 中工作

我对 React Native 中的状态概念还很陌生,无法使用它们来更改组件的状态。我有三个文本组件,一个是问题,另外两个是答案(是和否),另一个文本组件检查我对问题的回答是否已写,因此检查文本组件。当我针对某个问题单击“是”时,如果答案为“是”,则最后一个检查组件的状态应更改为“正确”,如果答案为“否”,则更改为“错误”。所以基本上,这就是我想要做的:

这是我到目前为止所拥有的:

http://img2.mukewang.com/645ca9310001048d03530548.jpg

这是我得到的错误:

http://img4.mukewang.com/645ca93f0001078b03570752.jpg

这是我到目前为止的代码:


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} />


}


谁能告诉我怎么做?谢谢!


绝地无双
浏览 110回答 1
1回答

汪汪一只猫

像这样使用 useEffectuseEffect(() => {&nbsp;if (answer === 'Yes') {&nbsp; Alert.alert('Right')&nbsp;}&nbsp;if (answer === 'No') {&nbsp;Alert.alert('Wrong')&nbsp;}}, [ answer ])或按检查按钮&nbsp; &nbsp;const checkAnswer = () => {&nbsp; &nbsp; &nbsp;if (answer === 'Yes') {&nbsp; &nbsp; &nbsp; Alert.alert('Right')&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;if (answer === 'No') {&nbsp; &nbsp; &nbsp;Alert.alert('Wrong')&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;if (answer === 'answer') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Alert.alert('please answer')&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }设置检查按钮 onPress={checkAnswer}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript