Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 带三元运算符的ReactJs SyntaxError_Javascript_Reactjs - Fatal编程技术网

Javascript 带三元运算符的ReactJs SyntaxError

Javascript 带三元运算符的ReactJs SyntaxError,javascript,reactjs,Javascript,Reactjs,下面的代码显示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

下面的代码显示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}
(that.props.actionType==“意见”)
?
{that.state.\u CmtCnt?:null}
:
{that.state.\u CmtCnt?:null}

您需要使用普通括号进行分组。大括号只能在jsx表达式中使用

that.props.actionType == "opinion"
  ? (that.state._CmtCnt ? <ViewAnswer isFullView={that.props.isFullView} /> : null)
//  ^                                                                             ^
  : (that.state._CmtCnt ? <ViewComment isFullView={that.props.isFullView} /> : null)
//  ^                                                                              ^
that.props.actionType==“意见”
? (该.state.\u CmtCnt?:null)
//  ^                                                                             ^
:(该.state.\u CmtCnt?:空)
//  ^                                                                              ^
基本语法是:

状况?表达式1:表达式2

这是因为您将
{}
与expression1和expression2一起使用,请删除这一点,
{}
是我们在JSX中放置JS表达式所必需的。按照您使用的方式,这意味着您试图返回一个对象,错误是因为键无效

这样写:

(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)
(that.props.actionType==“意见”)?
(该.state.\u CmtCnt?:null)
:
(该.state.\u CmtCnt?:null)

您应该编写更容易理解的代码,而不是复杂的嵌套数据,它们之间的变化很小-您所选择的只是选择一个要使用的组件,因此将其向上移动,您将得到更易于阅读的代码,而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
}
const Renderer=that.props.actionType==“意见”?ViewAnswer:ViewComment
// ...
{那个州。{u CmtCnt&&}
//或
{那个州.\u CmtCnt?
:
无效的
}

不确定您为什么要使用
等上下文别名,或
有点过时,您倾向于将上下文保留到实例并正确绑定

,可能是因为语法错误。如果没有更多的上下文,这将很难帮助您。谢谢Mayank,通过将括号从{}改为()它可以工作。