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

使用react-native-banner-carousel加载本地图片报错:JSON值'2'无法转为NSString

解决react-native-banner-carousel加载本地图片时"NSNumber无法转换为NSString"的错误

嘿,这个问题我之前也踩过坑!咱们来看看问题出在哪:

你遇到的json value '2' of type nsnumber cannot be converted to nsstring错误,根源是本地图片的加载方式用错了:

  • 用require("./abc.jpg")导入本地图片时,React Native会把它转换成一个数字类型的资源ID(比如报错里的2),而不是字符串格式的URI;
  • 但你在<Image>组件里写了source={{uri:image}},uri字段只接受字符串类型的网络地址或本地文件路径,把数字类型的资源ID传进去,自然就触发了类型转换错误。

修正方案:直接使用require返回的资源ID

你不需要套一层uri,直接把require返回的结果传给source就可以了,修改你的renderPage方法:

renderPage(image, index) {
  return (
    <View key={index}>
      <Image style={{ width: BannerWidth, height: BannerHeight }} source={image} />
    </View>
  );
}

完整的修正后代码

这里给你贴好完整的组件代码,直接替换就行:

import React from 'react';
import { View, Image, Dimensions, StyleSheet } from 'react-native';
import Carousel from 'react-native-banner-carousel';

const BannerWidth = Dimensions.get('window').width;
const BannerHeight = 260;
const images = [ require("./abc.jpg"), require("./xyz.jpg") ];

export default class ImageSlider extends React.Component {
  renderPage(image, index) {
    return (
      <View key={index}>
        {/* 直接传入require返回的资源ID,不用uri包裹 */}
        <Image style={{ width: BannerWidth, height: BannerHeight }} source={image} />
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <Carousel 
          autoplay 
          autoplayTimeout={5000} 
          loop 
          index={0} 
          pageSize={BannerWidth} 
        >
          {images.map((image, index) => this.renderPage(image, index))}
        </Carousel>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    justifyContent: 'center'
  },
});

额外提醒

  • 加载网络图片时,才需要用source={{uri: '网络图片地址'}}的格式;
  • 加载本地图片时,要么直接在source里写require('./路径'),要么把require的结果存到数组里再传递,千万别套uri哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:43:26