Failed to compile, Unexpected token if in ReactJS

后端 未结 2 1858
情深已故
情深已故 2020-12-22 04:29

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

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


        
2条回答
  •  孤城傲影
    2020-12-22 04:50

    JSX only allows expressions, not statements. The ternary operator is an expression. if starts an if statement. You can see why an if statement wouldn't work by looking at the compiled JavaScript (with the if statement removed):

    {
      loading || Object.keys(product).length <= 0 ? 'loading' : React.createElement(
        'div',
        null,
        React.createElement(ProductPictureWidget, { mainPic: product.pic_url }),
        React.createElement(ProductOptionsWidget, { product: product, activeProps: activeProps, selectProductOption: undefined.selectProductOption })
      );
    }
    

    JSX amounts to function calls and object declarations. If the if statement were compiled, it would yield invalid JavaScript:

    {
      loading || Object.keys(product).length <= 0 ? 'loading' : React.createElement(
        'div',
        null,
        if(){ }, // This is **invalid** JavaScript!!
        React.createElement(ProductPictureWidget, { mainPic: product.pic_url }),
        React.createElement(ProductOptionsWidget, { product: product, activeProps: activeProps, selectProductOption: undefined.selectProductOption })
      );
    }
    

提交回复
热议问题