首页 > 解决方案 > React Native 中的条件渲染

问题描述

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

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

否则isPlayer === true && base.length > 1,渲染 y

否则渲染 z

下面是我正在处理的代码片段,我已经标记了需要渲染文本的位置。我尝试用 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>

标签: javascriptreactjsreact-nativeconditional-statements

解决方案


<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/>;
}

阅读内容以获取更多信息。


推荐阅读