繁体   English   中英

如何在React Native中进行条件渲染

[英]How to do conditional rendering in react native

如何在超过1个条件的本机反应中进行条件渲染?

以下是我的代码的一部分

指数

 .then(response => response.json())
          .then((responseData) => {
             this.setState({
           progressData:responseData,
          });
    .....
    ......
      render() {

        const { progressData }= this.state;
      return(
        <View style={{flex:1}}>
        <HeaderExample />
        <View>
         {progressData == "1"} 
               (<View>

                 <Text style={{fontSize:28,color:"#8470ff",fontWeight: 'bold',paddingTop:20,alignSelf:'center'}}>Pending</Text>

                </View>)}
{  progressData == "2" && 
           (<View>
             <CardSection>
             <Text style={{fontSize:28,color:"#8470ff",fontWeight: 'bold',paddingTop:20,alignSelf:'center'}}>InProgress </Text>

             <View style={styles.buttonContainer}>
             <Button
             title="Report"
             color="#8470ff"
             onPress={() =>onPressReport()}
             />

             </View>)}

但是这里仅是一种情况,即responseData仅包含一个字段。 但是现在reponseData包含2个数组。 每个都有3个对象。 所以,我怎么在这里检查条件呈现?我responseData看起来像这样 我想在每个条件下填充一些UI。 这意味着if status = 1 && work_type ="plumber"则呈现一些UI。 同样, if status = 2 && work_type="electrical" && assigend_to="worker_45"则呈现一些ui。 那么我该怎么做呢?

请帮忙

您可以将渲染移到新的变量或函数中。 保持清晰的render功能

 render() {

        const { progressData }= this.state;
      return(
        <View style={{flex:1}}>
        <HeaderExample />
        <View>
        {renderProgressData(progressData)}
        ... //rest of your code
      )
  }

在您的renderProgressData函数中,您可以创建一个switch

renderProgressData = (progress) => {
   switch(progress) {
    case 1:
        return (<View>1</View>)
    case 2:
         return (<View>1</View>)
    // ...  and so on
    default:
        return (<View>Default View</View>)
   }
}

这样对我来说更干净一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM