在React native 如何写if判断和for循环

2023-06-25,,

在vue中一般在需要判断时都是通过if语句来实现的,但是在react native中一般则通过三元运算法来实现。

具体代码如下所示。

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>
)
}
}

也可以这样

{index== ?(
<View style={styles.center}>
<p>index为1时有内容,不为1时为空</p>
</View>
) : (
<Text />
)}

其实两种写法差不多,也都很容易理解,就不多说了。

再说一下在react native中如何进行循环

import React from 'react';
import { View, Image, TextInput, Text } from 'react-native';
class BindCard extends React.Component {
constructor(props) {
super(props);
this.state = {
list: [,,,,],
data:[{
id:,
list:[,,]
},{
id:,
list:[,,]
}]
};
} 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>
)
}
}

上面就是关于react native 中的条件判断和循环的写法了,希望对你有帮助。

在React native 如何写if判断和for循环的相关教程结束。

《在React native 如何写if判断和for循环.doc》

下载本文的Word格式文档,以方便收藏与打印。