简体   繁体   中英

Rendering based on Enum in ReactJS

In App.js

import "./styles.css";
import { IconType }, Icon from "./icons"; //<-this line gives syntax error

export default function App() {
    return <Icon icon=IconType.Complete/>
};

In icon.js

import React, { useMemo } from 'react';

export enum IconType //<-this line gives syntax error
{
     Complete,
     Active,
     Risk,
     Overdue
}
const Icon = ({ props }) => {
     if (props.icon === IconType.Complete){
       return <h1>icon</h1>
     }
}

export default Icon;

See codesanbox

How should I fixed the syntax error above marked in the comment?

You are getting an error and you can observe from the description 'enum' declarations can only be used in TypeScript files .

From the documentation.

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript.

Read this for better understanding.

Enum is a feature used in typescript and it can not be used in .js files.

So, the first way is to install typescript and rename the .js to .tsx . The file extension of .tsx let you can write typescript and jsx . For more explanation please reference this .

I have been improved on this changes and this is a workable example codesanbox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM