简体   繁体   中英

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

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

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

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>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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