使用三元运算符的ReactJs SyntaxError

时间:2018-01-15 15:45:38

标签: javascript reactjs

enter image description here下面的代码显示了ReactJs组件中的语法错误:

(that.props.actionType == "opinion")
?
{that.state._CmtCnt?<ViewAnswer isFullView={that.props.isFullView?true:false} />:null}
:
{that.state._CmtCnt?<ViewComment isFullView={that.props.isFullView?true:false} />:null}

3 个答案:

答案 0 :(得分:1)

基本语法是:

  

条件?表达式1:表达式2

这是因为你正在使用带有expression1和expression2的{},删除它,当我们想把JS表达式放在JSX中时需要{}。您正在使用的方式,这意味着您正在尝试返回一个对象,而错误是因为密钥无效。

像这样写:

(that.props.actionType == "opinion") ?
    (that.state._CmtCnt?<ViewAnswer isFullView={that.props.isFullView?true:false} />:null)
:
    (that.state._CmtCnt?<ViewComment isFullView={that.props.isFullView?true:false} />:null)

答案 1 :(得分:0)

您需要使用普通括号进行分组。大括号仅适用于jsx表达式。

that.props.actionType == "opinion"
  ? (that.state._CmtCnt ? <ViewAnswer isFullView={that.props.isFullView} /> : null)
//  ^                                                                             ^
  : (that.state._CmtCnt ? <ViewComment isFullView={that.props.isFullView} /> : null)
//  ^                                                                              ^

答案 2 :(得分:0)

你应该编写更易于理解的代码,而不是复杂的嵌套terinary,它们之间几乎没有变化 - 你选择的只是选择要使用的组件,所以将其向上移动,最后用JSX中的逻辑更少,更容易阅读代码

const Renderer = that.props.actionType == "opinion" ? ViewAnswer : ViewComment
// ...

{that.state._CmtCnt && <Renderer isFullView={!!that.props.isFullView} />}
// or
{that.state._CmtCnt ? 
  <Renderer isFullView={!!that.props.isFullView} /> :
  null
}

不确定您使用that的原因 - 对于selfthat等上下文的别名有点过时,您往往希望将上下文保留到您的实例中正确绑定