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

How to do conditional rendering in react native

如何在超过 1 个条件的情况下在 React Native 中进行条件渲染?

以下是我的部分代码

索引

 .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 看起来像 this。我想在每个条件下填充一些 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>)
   }
}

这样对我来说比较干净