javascript - 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/>;
}
阅读此内容以获取更多信息。
推荐阅读
- sql-server - 将值插入 SQL 中的简单表时出现什么问题?
- database - 如何搜索 100 亿条记录?
- generics - 是否可以编写一个通用的 rust 函数来告诉您给定的枚举变体是否在容器中?
- c# - C# 从字段继承属性
- python - 如何以更有效的方式实现这个数组算法?
- javascript - context.fillText() 输出在更新要显示的内容时被覆盖
- clickatell - Clickatell 在交易日触发
- r - 所有字符列的正确大写
- include - 内部未解决的包含
头文件 - python - 我可以在 Linux 中创建 Docker 容器以在 Unix 上使用它吗?