LoginSignup
2
2

More than 3 years have passed since last update.

[react-native]FlatListの使い方

Last updated at Posted at 2020-12-01

目的

App.jsにを表示する。レンダーする要素は別コンポーネント化。

App.js

import React, { useState } from 'react';
import { 
  StyleSheet, 
  View, 
  FlatList 
} from 'react-native';

import GoalItem from './components/GoalItem';

export default function App() {

  const [courseGoals, setCourseGoals] = useState([]);

  //courseGoalsには以下のような配列が入っている。
 Array [
   Object {
     "id": "0.1283113872926156",
     "value": "Aaa",
   },
   Object {
     "id": "0.1515628656002196",
     "value": "Aaa",
   },
 ]
 //

  return (
    <View style={styles.screen} >
      <FlatList 
        keyExtractor={(item, index) => item.id } //デフォルト値なので省略可
        data={courseGoals}   // ここに繰り返したい配列をいれる。※要素はstringである必要がある
        renderItem={itemData => <GoalItem id={itemData.item.id} title={itemData.item.value} />} 
     // viewの部分 引数itemDataの.itemプロパティに配列の要素が一つづつ繰り返し入ってくるような感じ
      />
    </View>
  );
}

GoalItem.js

レイアウトは任意

import React from 'react';
import { View, Text, StyleSheet,TouchableOpacity } from 'react-native';

const GoalItem = props => {
  return (
  <TouchableOpacity>
    <View>
      <Text>{props.title}</Text>
    </View>
  </TouchableOpacity>
  );
};


export default GoalItem;

所感

意外と癖が強い。
繰り返しの部分はそれぞれにユニークなkeyを指定しないとreact nativeが警告を出す。
特定のリストを消す時にfilterメソッドを使ったりする時にも使える。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2