【问题标题】:Conditionally Rendering in React NativeReact Native 中的条件渲染
【发布时间】:2020-12-28 09:25:09
【问题描述】:

我对本机和一般编码反应很陌生。我需要根据一些变量来渲染文本(见下文)。

如果 isPlayer === true && base.length === 1 ,渲染 x

else if isPlayer === true && base.length > 1 ,渲染 y

否则渲染 z

下面是我正在处理的代码的 sn-p,并且我已经标记了需要渲染文本的位置。我尝试用 if/else 逻辑编写一个函数,然后调用该函数,但没有让它工作。我知道使用 JSX,您可以进行内联条件渲染,但也无法使其正常工作。任何和所有的帮助表示赞赏!提前致谢!

<View style={{ marginTop: marginTopAdj, flexDirection: 'row' }}>
          <TouchableOpacity onPress={() => navigation.goBack()} style={{}}>
            {IconWhiteBackButton}
          </TouchableOpacity>

          <HeaderTitle
            containerStyle={styles.headerTitleContainer}
            textStyle={{ color: '#fff' }}
          >
            {Item to be conditionally rendered}
          </HeaderTitle>
</View>

【问题讨论】:

    标签: javascript reactjs react-native conditional-statements


    【解决方案1】:
    <View style={{ marginTop: marginTopAdj, flexDirection: 'row' }}>
              <TouchableOpacity onPress={() => navigation.goBack()} style={{}}>
                {IconWhiteBackButton}
              </TouchableOpacity>
    
              <HeaderTitle
                containerStyle={styles.headerTitleContainer}
                textStyle={{ color: '#fff' }}
              >
                {isPlayer === true && base.length === 1 && <ItemX/>}
                {isPlayer === true && base.length > 1 && <ItemY/>}
              </HeaderTitle>
    </View>
    

    对于更复杂的逻辑,创建一个新函数:

    renderItemConditionally = () => {
      if (...) return <ItemX/>;
      else if (...) return <ItemY/>;
      else return <ItemZ/>;
    }
    

    阅读this了解更多信息。

    【讨论】:

    • 感谢@Tobias Wälde!我不会很快忘记它现在是如何工作的。我很感激!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2021-08-21
    • 2022-01-17
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多