【问题标题】:Error using require with react native in javascript在 javascript 中使用 require 和 react native 时出错
【发布时间】:2018-10-01 06:07:30
【问题描述】:

我正在尝试这样做:

<Image source={require(`../../imagens/cards${result.color}.png`)}/>

在该路径中,我有 5 个 png 文件:cardsgreen、cardyellow、cardspurple、...

result.color 给了我一个紫色的字符串,它不起作用,因为 require 不允许它,我想知道是否有其他方法可以做到这一点,我也尝试过:

source={{ uri: `../../imagens/cards${result.color}.png` }}

它也不起作用,在那种情况下图像没有打开

错误:开发服务器返回响应错误代码:500,调用要求只需要 1 个字符串文字参数

【问题讨论】:

    标签: javascript image react-native require


    【解决方案1】:

    尝试使用:

      var images = {
                    blue: require('../imageblue.png'),
                    red: require('../imagered.png')
                }
    <Image source={images[this.state.imgColor]} key={images[this.state.imgColor]} />
    

    ImgColor 应该是你的 result.color。 不要忘记在图像上使用key,否则状态不会动态改变它的颜色。

    【讨论】:

    • 这样不行,我也试过 '../../imagens/cards'+result.color+'.png' 还是不行
    • 然后在源代码上使用之前尝试编写路径。如果您必须重新加载它,请将其用作状态。喜欢this.state.imgPath = '../../imagens/cards/' + result.color.toString() + '.png' 并在require 中使用这个imgPath。
    • 是的,我做到了,实际上是使用toString(),然后尝试在require中使用它,同样的错误
    • 我能想到的唯一解决方案是 if(result.color === 'purple') 然后我使用 require('../imagens/cardspurple.png')
    • @PedroMartinsMelo 我更新了答案,它比if case 更优雅和更炫
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多