如何编写 if else 在返回 反应本机.



希望你过得好。

遇到了小问题,只有当我的条件为真时,我才想传递标签。

例如:

render(
   return(
     <View>
         {
          if(data==='test')
            {
              <Text>Hello this is Test Execution </Text>
            }
         }
     </View>
   )
)

我想完全像上面的例子一样做。

得到一些错误,我不明白该怎么做,所以请帮助我。

谢谢

一种简短而安全的方法是使用三元运算符并在 false 的情况下呈现null

{ data === 'test' ? <Text>Hello this is Test Execution </Text> : null }
你可以

试试像

{(data === 'test')  && <Text>Hello this is Test Execution</Text>}

希望这会有所帮助。

您需要编写一个可以选择呈现文本的函数。

  renderText(data) {
      if (data === 'test') {
         return  <Text>Hello this is Test Execution </Text>; 
      }
  }
  render() {
      return(
          <View>
              {this.renderText(data)}
          </View>
      );
  }

你可以试试这个:

render(
   return(
     <View>
         { (data==='test') && <Text>Hello this is Test Execution </Text>}
     </View>
   )
)

但我建议使用以下语法:

render(
  if (data === 'test') {
     return (
        <View>
          <Text>Hello this is Test Execution </Text>
        <View>
     )
  }
  return null;
)

你可以这样做

return(){
    <View>
    {data === 'test' && <Text>Hello this is Test Execution </Text>}
    </View>
}

最新更新