Representación condicional en React Native

Sep 10 2020

Soy bastante nuevo para reaccionar de forma nativa y la codificación en general. Necesito renderizar texto basado en algunas variables (ver más abajo).

si isPlayer === true && base.length === 1, renderizar x

si no isPlayer === true && base.length > 1, render y

más render z

A continuación se muestra el fragmento de código en el que estoy trabajando y he marcado dónde necesito representar el texto. He intentado escribir una función con lógica if / else y luego llamar a la función, pero no he conseguido que funcione. Sé que con JSX puede hacer renderizado condicional en línea, pero tampoco ha podido hacerlo funcionar. ¡Se agradece cualquier ayuda! ¡Gracias por adelantado!

<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>

Respuestas

1 TobiasWälde Sep 10 2020 at 05:16
<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>

Para una lógica más compleja, cree una nueva función:

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

Lea esto para obtener más información.