gpt4 book ai didi

react-native - React Native 要求不适用于图像源

转载 作者:行者123 更新时间:2023-12-01 12:24:50 25 4
gpt4 key购买 nike

给出下面的代码,响应本地提示

Requiring unknown module "../../images/Foo.png".If you are sure the module is there, try restarting the packager or running "npm install".

But the same code works fine if I hardcode the image source path in require call.

Code not working: has a method call to determine icon name. Notice the require('../../images/'+imageIconNameFor(prediction.type) line.

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 native 版本是 0.37.0。我在 ios-simulator 上对此进行了测试。

最佳答案

不幸的是,这就是 react-native packager 的工作方式,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} />

关于react-native - React Native 要求不适用于图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41033746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com