简体   繁体   中英

React <Text> with ternary conditional operator

I am pretty new to react-native and I don't know how to find a solution for what I am trying to achieve. I have multiple functions which either return null or a string. I want to show the return value when it's not null. for example my functions are

//these functions either return null or a string
const a =() => { ...};
const b =() => { ...};
const c =() => { ...};

I have a <Text> component and I want to show the return values from the functions inside my <Text> component.

Right now I am doing it in the following way

<Text>
  {a()}{b()}{c()}
</Text>

Now everything works fine and The text will only show the return value when it is a string.

I want to add a ternary conditional operator and check whether a new variable tmp is undefined or not. if tmp is not undefined the <Text> should show tmp value otherwise It should show the return value of the function that I have above.

<Text>
  {tmp !== undefined ? tmp : }{a()}{b()}{c()}
</Text>

if I do something like

<Text>
  {tmp !== undefined ? tmp : (
  a();
  b();
  c();
  )}
</Text>

and if tmp is undefined it will show the null returned from function too. but I don't want the null returned from functions to be show like the first example.

Could your a , b , and c functions return an empty string instead of null ?

If so, you could rewrite your answer as:

<Text>{tmp || `${a() + b() + c()}`}</Text>

If not, it's a little more cumbersome to write, but the same idea would work:

<Text>{tmp || `${a() || ''}${b() || ''}${c() || ''}`}</Text>

There are multiple ways to accomplish this, In React Native you can have nested <Text> components. Insted of using a ternary operator, I would do it like this:

<View>
  {tmp && (
    <Text>
      {_a && <Text>{_a}</Text>}
      {_b && <Text>{_b}</Text>}
      {_c && <Text>{_c}</Text>}
    </Text>
  )}
</View>

See the snack https://snack.expo.dev/@abranhe/undefinedvalues

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