React native if判斷和for迴圈的寫法
阿新 • • 發佈:2019-01-02
- if判斷的寫法
import React from 'react'; import { View, Image, TextInput, Text } from 'react-native'; class BindCard extends React.Component { constructor(props) { super(props); this.state = { errorMsg: "" }; } render(){ let {errorMsg} = this.state; return( <View> //這裡要寫父標籤,要不會報錯 { errorMsg && <Text>{errorMsg}</Text>} //如果有錯誤資訊,就顯示,沒有就不顯示 //三元運算用法 {errorMsg ? <Text>{errorMsg}</Text> : "" } </View> ) } }
- for迴圈寫法
import React from 'react'; import { View, Image, TextInput, Text } from 'react-native'; class BindCard extends React.Component { constructor(props) { super(props); this.state = { list: [1,2,3,4,5], data:[{ id:1, list:[1,2,3] },{ id:2, list:[4,5,6] }] }; } keyExtractor = item => item.id; renderItem = ({ item, index }) => { return <Text>{item},{index}</Text>; }; render(){ let {list} = this.state; return( <View> //這裡要寫父標籤,要不會報錯 //第一種寫法 { list && list.map(info,index)=>( <Text>{info},{index}</Text> )} //第二種寫法 {list.map((info, index) => { return ( <Text>{info},{index}</Text> ); })} //第三種寫法 <FlatList data={list} keyExtractor={this.keyExtractor} renderItem={this.renderItem} style={{ height: ‘500px’}} /> //雙迴圈寫法 { data.map(item,index)=>( <View> { item.list.map(info,index)=>{ return( <Text>{info},index</Text> ) }} </View> ) } </View> ) } }