4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[React Native] 配列要素をループで表示する

Last updated at Posted at 2019-09-02

概要

通常render()のreturn内ではfor文を書けないが、配列で管理されてるデータをText等で出力したい。

実装

Sample.tsx
export class Sample extends React.Component {
  render() {
    var alphabet = ["A", "B", "C", "D", "E"];

    return (
      <View>
        { 
          alphabet.map( data => { return (<Text key={data}>{data}</Text>) } ) 
        }
      </View>
    );
  }
}
  • {}で括っても、ifやforなどのロジックは呼び出せない。
  • 関数呼び出しは可能なので、mapを仕様してループ処理する。
  • ただし警告がでるので、keyを指定する。
  • keyは一意の値でなければならない。

終わりに

早い話が、mapを使おうなって話でした。
最初はreturnの前で予め表示用のデータを配列で作るという方法を考えていたのだが、普通にパフォーマンスが悪い。

export default class Sample extends Component {
  render() {
    var alphabet = ["A", "B", "C", "D", "E"];
    var Views: any[] = [];
    for (let i = 0; i < alphabet.length; i++) {
      Views.push(
        <View>{alphabet[i]}</View>
      );
    }

    return (
      <View>
        {Views}
      </View>
    );
  }
}
4
7
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
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?