React Native에서 조건부 렌더링

Sep 10 2020

나는 일반적으로 네이티브 및 코딩에 반응하는 것이 꽤 새롭습니다. 일부 변수를 기반으로 텍스트를 렌더링해야합니다 (아래 참조).

이면 isPlayer === true && base.length === 1x 렌더링

그렇지 않으면 isPlayer === true && base.length > 1y 렌더링

그렇지 않으면 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>

답변

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>

더 복잡한 논리의 경우 새 함수를 만듭니다.

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

자세한 정보는 이것을 읽으십시오 .