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>

解决方法

<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以获得更多信息。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...