【问题标题】:ReactJs Component Unexpected Token error on condition [duplicate]条件下的ReactJs组件意外令牌错误[重复]
【发布时间】:2018-08-17 20:48:26
【问题描述】:

我正在尝试检查道具是否为空并向反应组件添加条件。

代码如下:

class Mycomp extends Component {

    render() {
        return (
            <div className="Mycomp">
                {this.props.title}
                if (this.props.title != '') {
                    console.log('Title is not empty');
                }
            </div>
        );
    }
}

问题是我收到了 Unexpected Token 错误。

我该如何解决这个问题?

【问题讨论】:

  • if 条件移到return 语句之前。 (并使用!== btw)
  • 你不能拥有if statement in your JSX
  • { this.props.title || console.log("title is empty") }

标签: javascript reactjs


【解决方案1】:

你的 JSX 中不能有这样的 if 语句。您最好使用车削操作员或执行以下操作:

return (
  <div className="Mycomp">
        {this.props.title ||''} 
  </div>
);

【讨论】:

    【解决方案2】:

    你不能有 if-else 语句作为回报,使用三元运算符

    class Mycomp extends Component {
    
        render() {
            if (this.props.title != '') {
                console.log('Title is not empty');
            }
            return (
                <div className="Mycomp">
                    {this.props.title}
                    {this.props.title? 'Something here': 'Else something'}
                </div>
            );
        }
    }
    

    【讨论】:

      【解决方案3】:

      另一种选择是使用逻辑运算符 &&

      class Mycomp extends React.Component {
        render() {
          const title = this.props.title
          return (
            <div className="Mycomp">
               { title && title }
            </div>
          );
        }
      }  
      

      【讨论】:

      • 或者...{ title }
      猜你喜欢
      • 2018-09-10
      • 2014-01-21
      • 1970-01-01
      • 2015-08-18
      • 2019-02-19
      • 2017-10-07
      • 1970-01-01
      • 2019-05-26
      • 2016-05-03
      相关资源
      最近更新 更多