意外的关键字'this'reactjs jsx

时间:2019-07-30 13:16:05

标签: reactjs jsx

我是ReactJS的新手。我正在尝试在render return方法中放置一个条件以显示组件。 我收到以下错误。

./components/Layouts/Header.js
SyntaxError: /home/user/Desktop/pratap/reactjs/society/society-front/components/Layouts/Header.js: Unexpected keyword 'this' (14:8)

  12 |   render() {
  13 |     return (
> 14 |       { this.props.custom ? <CustomStyle /> : <DefaultStyle /> }
     |         ^
  15 |     );
  16 |   }
  17 | }

这是我的组件代码-

import React from "react";
import CustomStyle from "./CustomStyle";
import DefaultStyle from "./DefaultStyle";

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custom:this.props.custom
    }
  }
  render() {
    return (
      { this.props.custom ? <CustomStyle /> : <DefaultStyle /> }
    );
  }
}

export default Header;

1 个答案:

答案 0 :(得分:6)

显式返回JSX时,您不能返回运算符,请将代码包装在Fragment中:

  render() {
    return (
      <>{ this.props.custom ? <CustomStyle /> : <DefaultStyle /> }</>
    );
  }

或删除分隔符:

render(){
    return this.props.custom ? <CustomStyle /> : <DefaultStyle />
}