反应原生图像 - 未知的命名模块'../img/2.jpeg' [英] React-native image - unknown named module '../img/2.jpeg'
问题描述
我正在尝试修改 react-redux 教程代码.我正在尝试加载本地存储的图像并且路径保存在对象中.
I'm trying to modify a react-redux tutorial code. I'm trying to load images that are stored locally and the paths are saved in an object.
...
{
"id": 2,
"title": "Redux",
"subtitle": "A State of Mind",
"img": "../img/3.jpeg",
"description": "Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test."
},
...
我收到以下错误(我已经重新启动了几次模拟器)
I have got the following error (I've restarted the simulator a few times)
未知命名模块:'../img/3.jpeg'
Unknown named module: '../img/3.jpeg'
这是容器(eslint 也说 - 意外的 require())
Here's the container (eslint also says - unexpected require())
import React, { Component } from 'react';
import {
Text,
TouchableWithoutFeedback,
View,
LayoutAnimation,
Image
} from 'react-native';
import { connect } from 'react-redux';
import { CardSection } from './common';
import * as actions from '../actions';
class ListItem extends Component {
componentWillUpdate() {
LayoutAnimation.spring();
}
renderDescription() {
const { library, expanded } = this.props;
if (expanded) {
return (
<CardSection>
<Image
source={require(library.img)}
style={styles.imageStyle}
/>
<View>
<Text>{library.subtitle}</Text>
<Text style={{ flex: 1 }}>
{library.description}
</Text>
</View>
</CardSection>
);
}
}
render() {
const { titleStyle } = styles;
const { id, title } = this.props.library;
return (
<TouchableWithoutFeedback
onPress={() => this.props.selectLibrary(id)}
>
<View>
<CardSection>
<Text style={titleStyle}>
{title}
</Text>
</CardSection>
{this.renderDescription()}
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = {
titleStyle: {
fontSize: 18,
paddingLeft: 15
},
descriptionStyle: {
paddingLeft: 10,
paddingRight: 10
},
imageStyle: {
height: 100,
width: 100,
backgroundColor: 'black'
}
};
const mapStateToProps = (state, ownProps) => {
const expanded = state.selectedLibraryId === ownProps.library.id;
return { expanded };
};
export default connect(mapStateToProps, actions)(ListItem);
除了图像,一切正常 - 只是图像不存在.
Apart from the image, everything is working fine - just the image is not there.
推荐答案
你不能在 React Native 中动态地要求图片,要么静态地做,要么像这样使用 uri:
You can not dynamically require images in React Native, either do it statically, or use uri like this:
source={{ uri: library.img }}
但请考虑到您必须将图像放在此路径下
But take in consideration the you have to put your images under this path
anroid/app/src/main/res/drawable
创建 drawable
文件夹(如果未创建).
create drawable
folder if it's not created.
并更新json文件以删除../
and update the json file to remove the ../
请参考这个问题:https://github.com/facebook/react-native/issues/2481
这篇关于反应原生图像 - 未知的命名模块'../img/2.jpeg'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!