意外的关键字“this”reactjs jsx

15

我是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个回答

20

当你明确返回JSX时,不能返回三元运算符,将你的代码包装在一个Fragment中:

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

或者移除分隔符:

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

删除分隔符是一种比使用丑陋的Fragment更好的方法。谢谢。 - Mahendra Pratap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接