React native if判断和for循环的写法

版权声明:如要转发,请注明出处,小小喵的微博 https://blog.csdn.net/weixin_42881744/article/details/84566568
  1. 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>
		)
	}
}
  1. 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>
		)
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42881744/article/details/84566568