意外关键字 'this' reactjs jsx



我是ReactJ的新手。我正在尝试在渲染返回方法中放置条件以显示组件。我会收到以下错误。

./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;

明确返回JSX时,您无法返回三元运算符,将代码包装在Fragment中:

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

或卸下分隔符:

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

最新更新