【问题标题】:How to do conditional rendering in react native如何在本机反应中进行条件渲染
【发布时间】:2019-04-04 13:44:49
【问题描述】:

如何在超过 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 &amp;&amp; work_type ="plumber" 然后渲染一些 UI。 还有if status = 2 &amp;&amp; work_type="electrical" &amp;&amp; assigend_to="worker_45" 然后渲染一些用户界面。那我该怎么做呢?

请帮忙

【问题讨论】:

  • 尝试condition ? &lt;MyComponent /&gt; : null 而不是condition &amp;&amp; &lt;MyComponent /&gt;
  • 那么我该如何映射这里的每个元素呢?
  • 为什么要映射?具体如何?

标签: javascript reactjs react-native jsx conditional-rendering


【解决方案1】:

您可以在新变量或函数中移动渲染。清除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>)
   }
}

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

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多