我正在尝试修改 react-redux 教程代码。我正在尝试加载存储在本地的图像,并且路径保存在对象中。
...
{
"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."
},
...
我收到以下错误(我已经重新启动了模拟器几次)
未知命名模块:"../img/3.jpeg'
这是容器(eslint 也说 - 意外的要求())
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);
除了图像,一切都很好 - 只是图像不存在。
你不能在 React Native 中动态要求图像,要么静态地这样做,要么像这样使用 uri:
source={{ uri: library.img }}
但要考虑到您必须将图像放在此路径下
anroid/app/src/main/res/drawable
创建drawable
文件夹(如果未创建)。
并更新 JSON 文件以删除../
请参考本期:https://github.com/facebook/react-native/issues/2481