条件时ReactJs组件意外令牌错误

时间:2018-03-09 09:57:31

标签: javascript reactjs

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

以下是代码:

class Mycomp extends Component {

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

问题是我收到了一个意外的令牌错误。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

你的JSX中不能有if语句。你最好使用turnery操作员或做这样的事情:

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

答案 1 :(得分:1)

您不能使用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>
        );
    }
}

答案 2 :(得分:0)

另一个选择是使用逻辑运算符&amp;&amp;

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