javascript - use for loop in flatlist react native
问题描述
I'm beginner in react native, and I want to use for loop in flatlist to push require data,
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>
)
}
}
Like when pushing array from state using for loop
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;
};
Is there anyway to use looping in flatlist or we can't using any looping in list or flatlist in React Native.
解决方案
You can define a state
(array) and then loop through your required data and push them into the array state
. Then, pass that state into the data
prop
of the FLatlist
.
You can do something like this...
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>
);
}
}
Here, when the component mounts, it loops through the 'images' object and push them into an array called 'data' and store it to the state
. Then, that state
is passed to the Flatlist
as a prop
.
Please go through this and ask me if you have any further questions regarding this.
推荐阅读
- google-bigquery - BigQuery:用于将聚合数据与唯一数据合并的 SQL 查询
- javascript - Firebase 云消息传递:通知图标背景仅在第二次尝试时有效
- javascript - postgress node.js 函数响应不正确
- visual-studio - 无法在 Visual Studio 2012 中正确查看属性窗口
- php - 如何通过 PHP 在 localhost 中使用 Page Speed Insight API?
- python - 如何使用 pptx python 在 power point 中的字符之间创建空格?
- vue.js - Vue Vuetify 读取动态生成的 v-select 元素的选定选项
- pandas - 为大型数据集汇总数据框中的列
- java - 输入任意数字并使用while循环按降序打印所有奇数
- python-3.x - UnboundLocalError:分配前引用的局部变量“ckpt_path”