我试图通过URL和文本使用ListView加载图像并将数据显示到List中,但是当我在listview中填充图像和文本时,我的图像不会显示。
我的代码是:
import React, { Component } from "react";
import { ListView, Text, View, Image, StyleSheet } from "react-native";
const styles = Style.create({
container: {
flex: 1,
marginTop: 20
}
});
class ListViewDemo extends React.Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.state = {
dataSource: ds.cloneWithRows(["row 1", "row 2"])
};
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={data => {
<View style={styles.container}>
<Image
source={{
uri:
"https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg"
}}
style={{ width: 193, height: 110 }}
/>
<Text> Asad </Text>
</View>;
}}
/>
);
}
} [enter image description here][1]
export default ListViewDemo;
问题
图像不会在列表视图中呈现。
解
我注意到有时在组件呈现反应时出现图像时出现问题。特别是当它们通过网络呼叫加载时。我在你的style
中添加了一个image component
,将image source
放入变量并修复了代码中的一些语法错误。
最大的问题,以及它没有渲染图像的原因是你在你的{}
周围添加了renderRow prop
,这将需要一个return statement
。当您在()
周围供应return data
时,return
是隐含的,因为您使用的是fat arrow function
。
所以这,
renderRow = { (data) => { }}
成了这个,
renderRow={data => ( )}
例
您可以将整个组件复制并粘贴到代码中,它将起作用。这已经过测试,
import React, { Component } from 'react'; import { ListView, Text, View, Image, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20,
},
img: {
width: 193,
height: 110,
},
});
class ListViewDemo extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2']),
};
}
render() {
const imageSource = 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg';
return (
<ListView
dataSource={this.state.dataSource}
renderRow={data => (
<View style={styles.container}>
<Image
source={{ uri: imageSource }}
style={styles.img}
/>
<Text>{data}</Text>
</View>)}
/>
);
}
}
export default ListViewDemo;
概念证明
请参阅显示您的组件现在工作的图像,