反应,打字稿和道具类型:如何使用自己的类型?

问题描述 投票:0回答:1

我有一个字符串类型的文字,格式为type MyType = 'str1' | 'str2' | 'str3',我希望我的一个道具只接受这种类型,但是我不知道如何告诉PropTypes。

我曾尝试使用propTypes.oneOf(['str1', 'str2', 'str3']),但随后打字稿将其推断为普通字符串,这是我不想要的。

reactjs typescript react-proptypes
1个回答
1
投票

由于这是使用TypeScript进行类型检查,因此您不会尝试在React运行时级别(propTypes)进行操作,而是在TypeScript级别进行操作。

您的组件应在其props类型中使用字符串文字类型:

type MyComponentProps = {
    propName: MyType;
}

然后如果它是一个类组件:

class MyComponent extends React.Component<MyComponentProps, /*...your state type here...*/> {
    // ...
}

或者如果您使用的是功能组件:

const MyComponent = ({propName}: MyComponentProps) => {
    // ...
};
© www.soinside.com 2019 - 2024. All rights reserved.