Trouble requiring image module in React Native
刚开始使用React-Native时,我遇到了一些需要静态图像的麻烦。
这是到目前为止我拥有的非常基本的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | '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); |
主要故障区域是:
1 2 3 4 5 6 | <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中添加图像作为图像集,以便
...但无济于事。有人有什么想法吗?我已经阅读了文档,并且似乎正在按照规定的方式进行操作。谢谢!
自从React Native版本
只有拟议文档的屏幕截图:
更新:
现在有真实文档的链接:
https://facebook.github.io/react-native/docs/images.html
我有类似的问题,然后使用后缀和大小写将xcode项目的
例如,如果
您正在运行哪个版本的React Native?与此相关的打包程序存在一个已解决的问题。
在这种情况下,您可以使用以下命令更新或运行开发服务器:
1 | node_modules/react-native/packager/packager.sh --assetRoots path/to/Images.xcassets |
https://github.com/facebook/react-native/issues/282
该问题已经得到解答,但是如果您在Android上使用React Native,则可能会遇到相同的问题。对我来说,解决方案是使用
别忘了将图像添加到
NOTE: App build required for new resources
Any time you add a new resource to Images.xcassets you will need to re->build your app through XCode before you can use it - a reload from within >the simulator is not enough.
(from React Native docs https://facebook.github.io/react-native/docs/image.html#content)
还请确保重新启动打包程序。那为我解决了这个问题。
通过在资产文件夹中创建package.json文件,可以轻松引用图像。
项目文件夹结构
package.json
您可以通过此代码进行调用。
1 2 3 4 5 | <Image source={require('assets/img/avatar.png')} style={styles.itemAvatar} resizeMode={'cover'} /> |
对于静态图像,您需要提供以下路径:
1 2 | <Image source={require('./images/back.png')} style= {{width:25, height:25, marginLeft:12, padding:12}}/> |
这对我有用,对于存储在项目目录的images文件夹中的图像: