[英]react native: Ternary condition inside Text component
Is it possible to make ternary condition so that if {title} contains part of text such as "appl" then 'styles.label' will be change to 'styles.label_2'.是否可以制作三元条件,以便如果 {title} 包含部分文本,例如“appl”,则“styles.label”将更改为“styles.label_2”。
const Field = ({ title, info }: Props) => {
return (
<View style={styles.container}>
<Text style={styles.label}> {title} </Text>
<Text style={styles.info}>{info ? info : ''} </Text>
</View>
);
};
You can do that for sure.你肯定可以做到这一点。
The following checks if the title
string contains appl
and if so, use styles.label2
otherwise, use styles.label
以下检查
title
字符串是否包含appl
,如果是,则使用styles.label2
否则,使用styles.label
<Text style={title.includes('appl') ? styles.label2 : styles.label}> {title} </Text>
If you apply a second style only to hide when it evaluates to false, I prefer evaluating before rendering the component -- therefore if it evaluates to false, no component is ever present, instead of a empty one:如果您仅应用第二种样式以在计算结果为 false 时隐藏,我更喜欢在呈现组件之前进行评估——因此,如果它计算结果为 false,则永远不会存在任何组件,而不是一个空组件:
const Field = ({ title, info }: Props) => {
return (
<View style={styles.container}>
<Text style={styles.label}> {title} </Text>
{info && info.contains("appl") && (<Text style={styles.info}>{info} </Text>)}
</View>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.