编译失败,如果在 ReactJS 中出现意外标记 [英] Failed to compile, Unexpected token if in ReactJS

查看:52
本文介绍了编译失败,如果在 ReactJS 中出现意外标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法让这个简单的函数工作基本上我的标记就像这样(简化)

{ loading ||Object.keys(product).length <= 0 ?'加载':<div>{如果(){}}<ProductPictureWidget mainPic={product.pic_url}/><ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>

}

但这在我的 if 语句中留下了 SyntaxError: Unexpected token

我到底做错了什么,我不允许在我的速记 if 语句中使用 if 语句吗?

解决方案

JSX 不允许在返回函数中使用 if 语句.但是你可以使用三元表达式

{ loading ||Object.keys(product).length <= 0 ?'加载':<div>{(这里的条件)?<div>Hello World</div>: null}<ProductPictureWidget mainPic={product.pic_url}/><ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>

}

但是,如果您想使用 if 语句,还有另一种方法可以做到,即调用一个函数,在其中使用 if-else 语句

conditionalRender() {如果(条件){return 

你好

} 别的 {返回空值}}{ 加载 ||Object.keys(product).length <= 0 ?'加载':<div>{this.conditionalRender()}<ProductPictureWidget mainPic={product.pic_url}/><ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>

}

I cant seem to get this simple function to work basically my markup is like so(simplified)

{ loading || Object.keys(product).length <= 0 ? 'loading' :
  <div>
    {if(){

    }}
    <ProductPictureWidget mainPic={product.pic_url} />
    <ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>
  </div>
}

But this leaves me with SyntaxError: Unexpected token on my if statement

What exactly am I doing wrong here am I not allowed to do if statements within my shorthand if statement?

解决方案

JSX doesn't allow if statement within the return function. But you are allowed to use ternary expressions

{ loading || Object.keys(product).length <= 0 ? 'loading' :
  <div>
    {(condition here)? <div>Hello World</div>: null}
    <ProductPictureWidget mainPic={product.pic_url} />
    <ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>
  </div>
}

However if you want to make use of if statement there is an alternative way to do it, i.e to call a function within which you use the if-else statements

conditionalRender() {
   if(condition) {
      return <div>Hello</div>
   } else {
      return null
  }
}

{ loading || Object.keys(product).length <= 0 ? 'loading' :
  <div>
    {this.conditionalRender()}
    <ProductPictureWidget mainPic={product.pic_url} />
    <ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>
  </div>
}

这篇关于编译失败,如果在 ReactJS 中出现意外标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆