gpt4 book ai didi

reactjs - 意外的关键字 'this' Reactjs jsx

转载 作者:行者123 更新时间:2023-12-03 13:26:21 24 4
gpt4 key购买 nike

我是 ReactJS 新手。我试图在渲染返回方法中添加一个条件来显示组件。我收到以下错误。

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

关于reactjs - 意外的关键字 'this' Reactjs jsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57272649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com