You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native如何为useState关联的图片定义值?修复choice未定义报错

代码存在的核心问题:

  • 状态作用域错误:你把choice状态和setSelected更新方法定义在了没用的内部函数character里,App组件的渲染逻辑完全访问不到这两个变量,才会报choice未定义的错误,直接把状态定义移到App函数顶层,删掉多余的const character = () => {}包裹即可。
  • 组件使用错误:你用了Web端的<img>标签,React Native中要使用自带的<Image>组件渲染本地图片,属性也要从src改成source。
  • JSX结构错误:return里的View标签多了一个多余的闭合标签,会触发语法报错。
  • 注意需要先导入useState和React Native相关基础组件,否则也会出现运行报错。

修正后的完整代码:

import { useState } from 'react';
import { View, TouchableOpacity, Image, StyleSheet } from 'react-native';

// 可根据需求调整样式
const styles = StyleSheet.create({
  wrap: {
    flex: 1,
    padding: 20,
  },
  characterWrap: {
    marginBottom: 30,
  },
  choiceWrap: {
    margin: 10,
  }
})

export default function App() {
  const red = require('./assets/dummyRed.png');
  const blue = require('./assets/dummyBlue.png');
  const yellow = require('./assets/dummyYellow.png');
  const normal = require('./assets/dummy.png');

  const colours = { red, blue, yellow, normal }
  // 状态移到App组件顶层
  const [choice, setSelected] = useState(colours.normal)

  return (
    <View style={styles.wrap}>
      <View style={{alignItems : 'center'}}>
        <View style={styles.characterWrap}>
          {/* 替换为React Native官方Image组件 */}
          <Image source={choice} alt='colours' style={{width: 200, height: 200}} />
        </View>
      </View>
      <View style={{flexDirection:'row', alignItems:'stretch'}}>
        <TouchableOpacity onPress={() => setSelected(colours.yellow)} style={styles.choiceWrap}>
          <Image source={yellow} style={{ width: 100, height: 100 }} /> 
        </TouchableOpacity>
      </View>
    </View>
  );
}

内容的提问来源于stack exchange,提问作者visceraeffects

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:45:07