【问题标题】:react native require not working for image source反应本机需要不适用于图像源
【发布时间】:2017-04-23 08:35:12
【问题描述】:

给定下面的代码,反应原生抱怨

需要未知模块“../../images/Foo.png”。如果您确定该模块在那里,请尝试重新启动打包程序或运行“npm install”。

但如果我在require 调用中硬编码图像源路径,同样的代码也可以正常工作。

代码不工作:有一个方法调用来确定图标名称。注意require('../../images/'+imageIconNameFor(prediction.type) 行。

const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
    <View style={styles.predictionItem}>
        <Image style={styles.predictionIcon} source={require('../../images/'+imageIconNameFor(prediction.type))}></Image>
    </View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
    return "Foo.png";
}

代码工作:如果我在require 调用中硬编码图标名称,而不是调用方法来确定图标名称,它可以正常工作。注意require('../../images/Foo.png') 行。

const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
    <View style={styles.predictionItem}>
        <Image style={styles.predictionIcon} source={require('../../images/Foo.png')}></Image>
    </View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
    return "Foo.png";
}

当我连接字符串以构建图像源时,为什么会有不同的行为?
为什么require('../../images/'+imageIconNameFor(prediction.type) 无法渲染图像但require('../../images/Foo.png') 工作正常?

请注意,方法调用不是问题。错误消息包含使用方法调用计算的图像的完整路径。尽管有完整的路径,但 react native 抱怨缺少 require 的模块。
React 原生版本是 0.37.0。我在 ios-simulator 上对此进行了测试。

【问题讨论】:

    标签: react-native


    【解决方案1】:

    不幸的是,这就是 react-native 打包器的工作方式,require 中的图像名称必须是静态已知的。以下是来自官方docs的示例:

    // GOOD
    <Image source={require('./my-icon.png')} />
    
    // BAD
    var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
    <Image source={require('./' + icon + '.png')} />
    
    // GOOD
    var icon = this.props.active ? require('./my-icon-active.png') :     require('./my-icon-inactive.png');
    <Image source={icon} />
    

    【讨论】:

    • 谢谢。我忽略了文档。我假设 concate 有效。感谢您提供答案
    • 不工作的兄弟...我的图像路径来自 json,所以我必须在 require 函数中提供变量,所以我必须做什么
    • @M.HassamYahya 你可以改用source={{ uri: variable.urlPath }}
    猜你喜欢
    • 2021-03-02
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2021-09-26
    • 2019-12-18
    • 2018-05-16
    • 2020-04-16
    相关资源
    最近更新 更多