对空字符串使用条件渲染

时间:2020-01-29 20:29:57

标签: javascript reactjs react-native

我有一些反应本机代码可以读取对象。如果对象具有特定的属性,我希望它显示代码。最小化的代码块如下所示:

return <View>
      <Text>Title</Text>
      {item.mystring &&
               <View>
                     <Text>Should only be rendered when the mystring property exists and has a value</Text>
               </View>

       }
</View>

在大多数情况下,它可以正常工作,但是,如果属性mystring确实存在但具有空字符串,则会出现以下错误:

Invariant Violation: Text strings must be rendered within a <Text> component.

为什么我会在一个空字符串上收到此错误?我的首选是不渲染代码块。

2 个答案:

答案 0 :(得分:6)

此技巧仅适用于布尔值,null,undefined和0。即使它为空,React也会尝试渲染该字符串。

您可以将变量转换为布尔值:

{!!item.mystring &&
   <View>
         <Text>Should ...</Text>
   </View>
}

或使用三元运算符

{item.mystring ?
   <View>
         <Text>Should ...</Text>
   </View>
  :
  null
}

答案 1 :(得分:0)

这是通过react native发生的,实际上它会检查字符串作为值并给出错误。

import React from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

const TransitionFade = ({ children }) => {

    return(
        <TransitionGroup>
            <CSSTransition in={true} appear={true} timeout={700} classNames="fade">
                {children}
            </CSSTransition>
        </TransitionGroup>
    );

}

export default TransitionFade;

您可以执行类似的操作来解决此问题,或者首先将其解析为布尔值,例如return <View> <Text>Title</Text>> {item.mystring ? (<View> <Text>Should only be rendered when the mystring property exists and has a value</Text> </View>) : null } </View> 是一个字符串,并且它在渲染器内部,也就是外部文本,这会导致本机抛出错误,这是没有预料到的,但是自从过去2年以来一直在item.mystring中:/

相关问题