React Native点击按钮触发'Invalid hook call'错误,答题功能异常
React Native 答题校验功能 Invalid Hook Call 修复方案
问题根源定位
- 交互逻辑完全断链:将答案判定逻辑写在
useEffect中,依赖项设置为从未被赋值更新的store1状态,导致判定逻辑永远无法触发;且store1在整个流程中从未被正确赋值,点击校验时读取的永远是空值,没有实际判定能力 - 属性透传异常触发hook检测错误:
TextInput通过{...props}接收了大量非原生组件支持的自定义属性(包括题目文本、校验回调、结果文本等),加上无效的状态更新链路导致React渲染检测时判定hook调用顺序错位,最终抛出Invalid hook call错误 - 冗余的组件嵌套:将
Button嵌套在TouchableOpacity中,两层交互容器叠加没有实际作用,反而容易引发事件绑定冲突
核心修复步骤
- 移除冗余的中间状态和无效的
useEffect逻辑,不需要专门设置临时状态存储判定结果,直接在点击校验的回调中完成答案比对即可 - 重构点击校验回调逻辑,直接读取用户实时输入的答案做大小写兼容的比对,将判定结果直接赋值给用于页面展示的状态
- 修正Question组件的属性透传规则,仅将输入框需要的属性绑定到
TextInput上,其他自定义属性(题目文本、校验回调、结果文本)单独匹配到对应UI节点 - 移除多余的
TouchableOpacity嵌套,直接将点击回调绑定到Button组件的onPress属性上,简化交互结构
修复后可直接运行的代码
import React, { useState } from 'react'; import { StyleSheet, Text, View, ScrollView, Image, TextInput, Button } from 'react-native'; // 可复用通用答题组件 function Question(props) { return ( <View style={{ width: '90%', marginVertical: 12 }}> <Text style={{ fontSize: 16, marginBottom: 8 }}>{props.questionText}</Text> <TextInput style={{ height: 40, borderWidth: 1, paddingHorizontal: 12, marginVertical: 8, borderRadius: 4 }} value={props.inputValue} onChangeText={props.onInputChange} editable maxLength={40} multiline numberOfLines={4} /> <Button onPress={props.onCheckPress} title="提交校验" color="#841584" /> <Text style={{ marginTop: 8, fontSize: 15, fontWeight: 500 }}> {props.resultText} </Text> </View> ); } export default function App() { // 存储用户输入的答案 const [userAnswer, setUserAnswer] = useState(''); // 存储判定结果 const [checkResult, setCheckResult] = useState(''); // 点击校验时触发答案判定 const handleCheck = () => { const normalizedAnswer = userAnswer.trim().toLowerCase(); if (normalizedAnswer === 'yes') { setCheckResult('✅ 回答正确'); } else if (normalizedAnswer === 'no') { setCheckResult('❌ 回答错误'); } else { setCheckResult('⚠️ 请输入 Yes/No 格式的答案'); } }; return ( <ScrollView style={styles.container}> <View style={{ alignItems: 'center', paddingVertical: 20 }}> <Text style={styles.title1}>Quiz Time</Text> <Image source={require('./images/pic.jpeg')} style={styles.uriImg} /> <Question questionText='Is this Mt. Fuji? (Yes/No)' inputValue={userAnswer} onInputChange={setUserAnswer} onCheckPress={handleCheck} resultText={checkResult} /> </View> </ScrollView> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, title1: { fontSize: 22, fontWeight: 'bold', marginBottom: 16, }, uriImg: { width: 300, height: 200, resizeMode: 'cover', marginBottom: 20, } });
内容的提问来源于stack exchange,提问作者Isha
相关产品推荐
相关产品推荐

