我在我的 react 项目中使用流类型检查器。我有一个如下所示的组件:
// @flow
import React, { type Node } from 'react';
type Props = {
isLoading?: boolean,
children: Node,
modifier: '' | '--medium' | '--dark' | '--green',
}
const PulsingCircleLoader = ({ children, isLoading, modifier }: Props) => (
isLoading ?
<div class={`PulsingCircleLoader ${modifier}`}>
<div class="double-bounce1" />
<div class="double-bounce2" />
</div>
:
<span>{children}</span>
);
PulsingCircleLoader.defaultProps = {
isLoading: false,
modifier: '',
};
我使用 modifier
属性来切换组件的样式。现在我想保护自己不接收 blahblah
作为修饰符,但我想接收: '' 或 '--medium' 或 '--dark' 或 '--green'
或它们的组合,例如: --medium --green
。我怎样才能实现这个目标?
最佳答案
像这样使用UnionType
:
type Modifier = '' | '--medium' | '--dark' | '--green';
类型 Props 将为:
type Props = {
isLoading?: boolean,
children: Node,
modifiers: Modifier[],
}
并像这样使用它:
const PulsingCircleLoader = ({ children, isLoading, modifiers }: Props) => (
isLoading ?
<div class={`PulsingCircleLoader ${modifiers.join(' ')}`}>
<div class="double-bounce1" />
<div class="double-bounce2" />
</div>
:
<span>{children}</span>
);
关于javascript - Flow——字符串的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46911898/