在typescript中使用枚举强制有效的react props



我有这个button组件

import React from 'react';
enum ColorShape {
'blue',
'green',
'white',
'grey',
'black',
}
enum SizeShape {
'normal',
'small',
}
interface PropsShape {
text: string;
color: ColorShape;
size: SizeShape;
}
function Button({ text, color }: PropsShape) {
return (
<button className='Button'>
{text} {color}
</button>
);
}
export { Button, ColorShape, SizeShape };

我在这里用它

import { Button, ColorShape, SizeShape } from '../components/button';
...
<Button text='Log In'color='blue' size='normal' />

我已经阅读了文档,但我显然错过了一些东西,我想确保props是一个枚举值。

我得到的错误是
Type 'string' is not assignable to type 'ColorShape'.ts(2322)
button.tsx(18, 3): The expected type comes from property 'color' which is declared here on type 'I

我认为你使用错误的语法,试试这个:

enum ColorShape {
BLUE = 'blue',
GREEN = 'green',
WHITE = 'white',
GREY = 'grey',
BLACK = 'black',
};
enum SizeShape {
NORMAL = 'normal',
SMALL = 'small',
};
import { Button, ColorShape, SizeShape } from '../components/button';
...
<Button text='Log In'color={ColorShape.BLUE} size={SizeShape.NORMAL} />

相关内容

最新更新