简体   繁体   English

React Native 中的条件渲染

[英]Conditionally Rendering in React Native

I am pretty new to react native and coding in general.我对一般的原生和编码反应还很陌生。 I need to render text based on some variables(see below).我需要根据一些变量呈现文本(见下文)。

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

else if isPlayer === true && base.length > 1 , render y否则如果isPlayer === true && base.length > 1 ,则渲染 y

else render z否则渲染 z

Below is the snippet of code I am working on and I have marked where I need to render the text.下面是我正在处理的代码片段,我已经标记了需要呈现文本的位置。 I have tried writing a function with if/else logic and then calling the function but have not got it to work.我曾尝试用 if/else 逻辑编写一个函数,然后调用该函数,但没有让它工作。 I know with JSX you can do conditional rendering inline but have not been able to get that to work either.我知道使用 JSX 您可以内联进行条件渲染,但也无法使其正常工作。 Any and all help is appreciated!任何和所有的帮助表示赞赏! Thanks in advance!提前致谢!

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

For more complex logic create a new function:对于更复杂的逻辑,创建一个新函数:

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

Read this for further information.阅读本文以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM