简体   繁体   English

react js中的接口和枚举typescript

[英]Interface and enum typescript in react js

I am working on a project and I have a strange problem.我正在做一个项目,但我遇到了一个奇怪的问题。 i have an enum我有一个枚举

export enum ButtonTypes {
    Primary = 'primary',
    Secondary = 'secondary',
    Ghost = 'ghost',
}

and I want to use these enum values inside an interface我想在接口中使用这些枚举值

export interface IButtonProps extends React.HTMLProps<HTMLAnchorElement> {
    children: React.ReactNode;
    type: keyof typeof ButtonTypes;
}

but I got this error: Parsing error: Unexpected token但我收到了这个错误:解析错误:意外的令牌

11 | 11 | type: keyof typeof ButtonTypes;类型:按键类型的按键类型;

the error is indicating that there is an unexpected token after the keyof该错误表明在keyof之后有一个意外的令牌

the component code组件代码

export default function Button(props: IButtonProps) {
    const { children, type } = props;
    return (
        <Styles.ButtonWrapper type={ButtonTypes[type]}>
            {children}
        </Styles.ButtonWrapper>
    );
}

to have an complete picture on the code i have added my styled component code为了对代码有完整的了解,我添加了我的样式化组件代码

import styled from 'styled-components';
import { colors } from '../theme';
import { ButtonTypes } from './Button';

interface IButtonWrapperProps {
    type: ButtonTypes;
}
const BACKGROUND_MAP: any = {
    [ButtonTypes.Primary]: colors.primary,
};

const TEXT_COLOR_MAP: any = {
    [ButtonTypes.Primary]: colors.white,
};
const BORDER_COLOR_MAP: any = {
    [ButtonTypes.Primary]: colors.primary,
};

export const ButtonWrapper = styled.a<IButtonWrapperProps>`
    background-color: ${(props) => BACKGROUND_MAP[props.type]};
    color: ${(props) => TEXT_COLOR_MAP[props.type]}
    border: ${(props) => BORDER_COLOR_MAP[props.type]};
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 15px;
`;

I have fixed it, it is a problem in my package.json, all packages were very old I just have upgraded all packages and it worked fine.我已经修复了它,这是我的 package.json 中的一个问题,所有软件包都非常旧,我刚刚升级了所有软件包,并且运行良好。

don't be a fool like me, always keep an eye for your packages不要像我一样傻,时刻留意你的包裹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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