[英]use for loop in flatlist react native
我是 react native 的初学者,我想在 flatlist 中使用 for 循环来推送需要的数据,
render() {
return (
<View style={styles.container}>
<FlatList
data={[
require("./assest/image1.jpg"),
require("./assest/image2.jpg"),
require("./assest/image3.jpg"),
]}
renderItem={({ item }) => {
return <ListItem image={item} />
}}
keyExtractor={
(index) => {return index}
}
/>
</View>
)
}
}
就像使用 for 循环从 state 推送数组时一样
state ={
a: [12 , 13 , 14 ,15 , 19 ,21 ]
b: "1"
d = () => {
let c =[];
for (var i =0; i<= this.state.a.length - 1 ; i++) {
c.push( <child text = {this.state.a[i] />);
}
return c;
};
无论如何要在平面列表中使用循环,或者我们不能在 React Native 中的列表或平面列表中使用任何循环。
您可以定义一个state
(数组),然后遍历所需的数据并将它们推送到数组state
中。 然后,将 state 传递到prop
的data
FLatlist
中。
你可以做这样的事情......
import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import ListItem from '...'; //import the ListItem here
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
}
componentDidMount = () => {
let data = [];
const images = {
image1: require("./assest/image1.jpg"),
image2: require("./assest/image2.jpg"),
image3: require("./assest/image3.jpg"),
}
images.forEach(image => {
data.push(image);
this.setState({ data })
})
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={({ item }) => {return <ListItem image={item} />}}
keyExtractor={(index) => {return index}}
/>
</View>
);
}
}
在这里,当组件安装时,它会遍历“图像” object 并将它们推送到一个名为“数据”的数组中,并将其存储到state
中。 然后,将state
作为prop
传递给Flatlist
。
请通过此 go 询问我是否对此有任何进一步的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.