我有一个字符串类型的文字,格式为type MyType = 'str1' | 'str2' | 'str3'
,我希望我的一个道具只接受这种类型,但是我不知道如何告诉PropTypes。
我曾尝试使用propTypes.oneOf(['str1', 'str2', 'str3'])
,但随后打字稿将其推断为普通字符串,这是我不想要的。
由于这是使用TypeScript进行类型检查,因此您不会尝试在React运行时级别(propTypes
)进行操作,而是在TypeScript级别进行操作。
您的组件应在其props类型中使用字符串文字类型:
type MyComponentProps = {
propName: MyType;
}
然后如果它是一个类组件:
class MyComponent extends React.Component<MyComponentProps, /*...your state type here...*/> {
// ...
}
或者如果您使用的是功能组件:
const MyComponent = ({propName}: MyComponentProps) => {
// ...
};