【问题标题】:Activity Indicator Showing on Tab 1 as well as Tab 2 ( I only want it to be displayed on tab 2 - when tab 2 is loading)在选项卡1上显示的活动指示符以及选项卡2(我只希望它显示在标签2上 - 当加载时)
【发布时间】:2021-12-20 23:51:44
【问题描述】:

在下面的这段代码中,我创建了 2 个选项卡,使用状态来跟踪哪个选项卡是可见的。

currentTab === 1 & currentTab === 2

我对两者都使用三元运算符。 对于第二个选项卡,如果数据正在加载,我会显示一个活动指示器,并在数据加载完美时消失。 但是,即使我没有在第一个三元运算符而是在第二个运算符中使用它,活动监视器也会(连续)显示在选项卡 1 上。有什么建议吗?

<ScrollView style={{flex: 1}}>
                    {this.state.currentTab === 1 ? (
                      <View style={{flex: 1}}>
                          <Avatar
                            marginLeft={20}
                            rounded
                            source={{uri: image}}
                          />
                      </View>
                    ) : null}
                    {this.state.currentTab === 2 &&
                    this.state.metadata != null ? (
                      <View style={{flex: 1, paddingBottom: 20}}>
                        <Text style={styles.sectionHeader}> History</Text>
              
                      </View>
                    ) : (
                      <ActivityIndicator size="large" />
                    )}
                  </ScrollView>

【问题讨论】:

    标签: react-native conditional-operator uiactivityindicatorview


    【解决方案1】:

    您没有在第一个三元上使用 AtivityIndi​​cator,但它会显示,因为 三元运算符的工作原理是这样的:isTruthy ? true : false 如果 isTruthy 为真则执行 true,如果不是则执行 false

    在你的情况下

    • this.state.currentTab === 1 ? (&lt;&gt;&lt;/&gt;) : null 将在 currentTab 为 1 时返回您的选项卡,否则返回 null。

    • this.state.currentTab === 2 &amp;&amp; this.state.metadata != null ? (&lt;&gt;&lt;/&gt;) : (&lt;ActivityIndicator /&gt;) 将在 currentTab 为 2 并且元数据不为 null 时返回您的选项卡,如果不是则返回 ActivityIndi​​ciator。

    您的错误在于第二个三元运算符。如果 currentTab 不是 2 并且元数据为空,则您正在呈现 ActivityIndi​​cator。

    您可以为 ActivityIndi​​cator 创建第二个嵌套三元运算符来解决此问题。

    {this.state.currentTab === 2 ? (
      this.state.metadata != null ? (
        <View style={{flex: 1, paddingBottom: 20}}>
          <Text style={styles.sectionHeader}> History</Text>
    
        </View>
      ) : (
        <ActivityIndicator size="large" />
      )
    ) : null}
    

    在这种情况下,如果 currentTab 为 2,它将执行嵌套的三元组,如果不是,则返回 null。在嵌套的三元组中,如果 metadata 不为 null,它将返回您的选项卡,如果不为 null,则返回 ActivityIndi​​cator。

    【讨论】:

    • 很棒的描述 - 完美运行!我学到了很多!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多