如何访问json文件中的本地图像URL

Ste*_*han 5 json react-native

我在访问 json 文件中的本地图像 url 时遇到问题。以下是我尝试过的所有方法,但没有一个有效。

// json
{
    "image": "./images/example.jpg",
}

// React Native
import data from './data.json';

const URL =  JSON.stringify(data.image)   
<Image source = {{uri: URL } style = {{ width: 98, height: 22 }} />    // Image not showing

const URL = data.image
<Image source = {{uri: URL } style = {{ width: 98, height: 22 }} />    // Image not showing
Run Code Online (Sandbox Code Playgroud)

上述方法中图像未显示。

我也尝试使用 require 如下:

// json
{
    "image": "example.jpg",
}

const item =  data.image   
<Image source = {require( './images/' +  item)} style = {{ width: 98, height: 22 }} />

const item =  JSON.stringify(data.image) 
<Image source = {require( './images/' +  item)} style = {{ width: 98, height: 22 }} />
Run Code Online (Sandbox Code Playgroud)

上面显示了一个错误,要求只接受字符串文字参数,这对我来说很奇怪,因为下面的代码实际上有效。

const item = 'example.jpg'
<Image source = {require( './images/' +  item)} style = {{ width: 98, height: 22 }} />
Run Code Online (Sandbox Code Playgroud)

我在互联网上搜索了几个小时,但找不到解决方案。有人可以告诉我一个访问本地 json 数据的正确示例吗?多谢。

Ara*_*d S 2

不能在 require 中使用变量。所有要求都必须是可静态分析的。这意味着你总是必须编写 require('/path/to/file')。你可以尝试类似的东西

const images = {
    profile: {
        profile: require('./profile/profile.png'),
        comments: require('./profile/comments.png'),
    },
    image1: require('./image1.jpg'),
    image2: require('./image2.jpg'),
};

export default images;
import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}
Run Code Online (Sandbox Code Playgroud)

您可以在这里查看更多相关信息

我们故意不支持动态生成的图像名称,因为随着时间的推移,这使得管理资产变得非常困难,就像您不想做的那样

var MyComponent = require('./' + libName + typeOfComponent);

或类似的东西。像这样的动态图像名称生成也不适用于我们正在推出的新动态资产管理系统,该系统让您只需使用 cmd+R 即可动态添加和更新资产(不再需要添加到 Xcode 并重新编译)。