javascript-React Nati中需要图像模块出现问题
刚开始使用React-Native时,我遇到了一些需要静态图像的麻烦。
到目前为止,这是我非常基本的代码:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
Image,
View,
} = React;
var buzz = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Image source={require('image!bg')} style={styles.bg}>
<Text style={styles.welcome}>
Welcome to Buzz! iOS interface to
</Text>
<Text style={styles.welcomeHeader}>Charityware</Text>
</Image>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'transparent'
},
welcomeHeader: {
fontWeight: '600',
fontFamily: 'Helvetica',
color: '#fff',
fontSize: 50,
alignSelf: 'center'
},
bg: {
width: 400,
height: 300,
alignSelf: 'auto',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
},
});
AppRegistry.registerComponent('buzz', () => buzz);
主要的麻烦领域是:
<Image source={require('image!bg')} style={styles.bg}>
<Text style={styles.welcome}>
Welcome to Buzz! iOS interface to
</Text>
<Text style={styles.welcomeHeader}>Charityware</Text>
</Image>
打包并运行应用程序时,出现渲染错误:
我了解您需要在xcode中添加图像作为图像集,以便require
调用找到该图像并为此添加了图像集:
...但无济于事。 有人有什么想法吗? 我已经阅读了文档,并且似乎正在按照规定的方式进行操作。 谢谢!
从React Native版本0.14
开始,图像处理已针对iOS和Android进行了规范化,现在有所不同。 除了Github上非常清晰的提交说明外,我找不到任何文档:记录新资产系统。
仅有建议文档的屏幕截图:
更新:现在有真实文档的链接:[https://facebook.github.io/react-native/docs/images.html]
我遇到了类似的问题,然后使用后缀和大小写将xcode项目的source={require('image!Villagers')}
目录下的文件系统中的图像文件重命名,以匹配要加载的图像。
例如,如果source={require('image!Villagers')}
它需要精确命名为Villagers.png
、Villagers@2x.png
和Villagers@3x.png
的图像文件。如果文件名的“ @ 3x”部分不存在,则找不到图像。
您正在运行哪个版本的React Native? 打包程序存在一个与此相关的问题已解决。
在这种情况下,您可以使用以下命令更新或运行开发服务器:
node_modules/react-native/packager/packager.sh --assetRoots path/to/Images.xcassets
[HTTPS://GitHub.com/Facebook/react-native/issues/282]
这个问题已经得到解答,但是如果您在Android上使用React Native,则可能会遇到同样的问题。 对我来说,解决方案是使用src/main/res/drawable
而不是source={required('./bg.png')}
。
只是不要忘记在src/main/res/drawable
文件夹中添加图像。
注意:新资源需要应用程序构建 每当您向Images.xcassets添加新资源时,您都需要通过XCode重新构建应用程序,然后才能使用它-从模拟器内部重新加载是不够的。 (来自React Native文档[https://facebook.github.io/react-native/docs/image.html#content)]
另外,请确保重新启动打包程序。 那为我解决了这个问题。
您可以通过在资产文件夹中制作package.json文件来轻松引用图像。
项目文件夹结构
package.json
您可以通过此代码进行调用。
<Image
source={require('assets/img/avatar.png')}
style={styles.itemAvatar}
resizeMode={'cover'}
/>
对于静态图像,您需要提供以下路径:
<Image source={require('./images/back.png')}
style= {{width:25, height:25, marginLeft:12, padding:12}}/>
这对我有用,对于存储在项目目录的images文件夹中的图像: