React Native测验题图片与题目不匹配问题求助
React Native测验应用图片不随题目切换问题解决
问题描述
开发React Native测验应用时,数据文件中每个题目对应不同图片,但切换题目时图片始终固定显示某一张(比如固定显示第一个樱桃图,修改索引后固定显示草莓图),无法随题目切换更新。
代码示例
数据文件代码
export default data = [ { question: "1. How would you say 'Cherry' in Italian? ", image: require('../../assets/images/cartoon_cherry.png'), options: ["Mela", "Ciliegia", "Fragola"], correct_option: "Ciliegia" }, { question: "2. How would you say 'Strawberry' in Italian?", image: require('../../assets/images/strawberry.png'), options: ["Mela", "Ciliegia", "Fragola"], correct_option: "Fragola" }, ... ]
原渲染代码
const renderQuestion = () => { const windowHeight = useWindowDimensions().height; const windowWidth = useWindowDimensions().width; const question = data[0]; // 问题核心所在 return ( <View style={{ marginVertical: '5%', width: windowWidth < 500 ? '100%' : '60%', height: windowHeight > 500 ? '40%' : '90%' }}> {/* 题目计数器 */ } <View style={{ flexDirection: 'row', alignItems: 'flex-end', marginBottom: '5%' }}> <Text style={{color: 'black', fontSize: 15, opacity: 0.6, marginRight: 2}}>{currentQuestionIndex+1}</Text> <Text style={{color: 'black', fontSize: 15, opacity: 0.6}}>/ {allQuestions.length}</Text> </View> {/* 题目文本 */ } <Text style={{color: 'black', fontSize: 22, paddingTop: '-50%'}}> {allQuestions[currentQuestionIndex]?.question} </Text> <View> <Image source={question.image} style={{ width: 100, height: 100 }} /> </View> </View> ) }
问题原因
渲染代码中固定取了数据数组的第一个元素(const question = data[0];),没有根据当前题目索引currentQuestionIndex获取对应题目数据,导致图片始终显示第一个题目的内容,无法随索引切换更新。同时代码中混用了data和allQuestions两个数据源,容易造成逻辑不一致。
解决方法
将固定取第一个元素的代码,改为根据当前索引currentQuestionIndex获取对应题目,同时统一数据源:
const renderQuestion = () => { const windowHeight = useWindowDimensions().height; const windowWidth = useWindowDimensions().width; // 根据当前索引获取对应题目,和问题文本的数据源保持一致 const question = allQuestions[currentQuestionIndex] || {}; return ( <View style={{ marginVertical: '5%', width: windowWidth < 500 ? '100%' : '60%', height: windowHeight > 500 ? '40%' : '90%' }}> {/* 题目计数器 */ } <View style={{ flexDirection: 'row', alignItems: 'flex-end', marginBottom: '5%' }}> <Text style={{color: 'black', fontSize: 15, opacity: 0.6, marginRight: 2}}>{currentQuestionIndex+1}</Text> <Text style={{color: 'black', fontSize: 15, opacity: 0.6}}>/ {allQuestions.length}</Text> </View> {/* 题目文本 */ } <Text style={{color: 'black', fontSize: 22, marginTop: 10}}> {question.question} </Text> <View> <Image source={question.image} style={{ width: 100, height: 100 }} /> </View> </View> ) }
额外优化提示
- 添加
|| {}空值兜底,避免索引越界时出现报错 - 原代码中
paddingTop: '-50%'无效(React Native不允许padding为负数),改为marginTop: 10这类合理值控制间距
内容的提问来源于stack exchange,提问作者Susy
相关产品推荐
相关产品推荐

