LoginSignup
24
11

More than 5 years have passed since last update.

ReactNativeで簡単なfetchからFlatList→onPressまでのサンプルプログラム(CRNA)

Last updated at Posted at 2017-09-14

振り返り

このド素人記事から1週間・・・
【Windows版】本当に0からのReact Native環境構築

基本的なところは分かって来た気がします。

そこでベースとなるコードを書きましたので
少しでも参考になる方がいたら幸いです。


CRNAでfetchからFlatList→onPressまで

ネットだと部品ばかりの情報でかなり苦労したので
僕は全文載せる派でいきます (^^♪

基本的なものは書けているはずです。
タイトルに書いたfetch・FlatList以外でも
stateやライフサイクル・アローfunction・onPressなどなど
良く使いそうなものは使っています。

まだまだ素人コードだとは思うので
その点はご了承ください。


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

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {data: null};
  }

  componentWillMount() {
    this._fetch();
  }

  _keyExtractor = (item) => item.releaseYear;

  _fetch = () => {
    fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState( {data: responseJson['movies']} );
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>一覧</Text>
        </View>
        <View style={styles.body}>
          <FlatList
            data={this.state.data}
            extraData={this.state.data}
            keyExtractor={this._keyExtractor}
            renderItem={({item}) =>
              <View style={styles.movieView}>
                <Text
                  style={styles.movieText}
                  onPress={() => Alert.alert(item.title)}
                >
                  {item.releaseYear}{'\n\t'}{item.title}
                </Text>
              </View>
            }
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    marginTop: 30,
    padding: 10,
    borderStyle: 'solid',
    borderWidth: 1,
    alignItems: 'center',
    backgroundColor: '#c6e6fa',
  },
  body: {
    flex: 1,
  },
  footer: {
    padding: 10,
    borderStyle: 'solid',
    borderTopWidth: 1,
    alignItems: 'center',
    backgroundColor: '#c6e6fa',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  movieView: {
    padding: 10,
    borderStyle: 'solid',
    borderBottomWidth: 1,
  },
  movieText: {
    fontSize: 16,
    lineHeight: 25,
  },
});

キャプチャ

無題.png


どうでしょう?

何とかではありますが書けるようになって来たのかな?
と思えるぐらいにはなりました。
(正解が分からないので探り探りではありますが・・・)

これからはNavigationやWebViewなどもやっていきたいと思っていますので
参考になりそうだなと思ったら是非フォローお願いします (^^)✨

24
11
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
24
11