javascript - Flow——字符串的组合

标签 javascript reactjs flowtype

我在我的 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/

相关文章:

javascript - 如何让Angular的 'filter'过滤器深度过滤?

javascript - 基本的 create-react-app Jest 测试解释

javascript - 数组中的流协变属性

javascript - 如何在 react 中传递具有已知字段的对象作为 Prop

javascript - JavaScript 下拉菜单功能的问题

javascript - Google Sheets 脚本日期比较未返回预期结果

javascript - 为什么 React.js 在使用标记库时不加载 HTML 代码

javascript - REACT 中的 UnCaughtType 错误, Hook 事件处理程序时的 js

typescript - 在 TypeScript 中键入 compose 函数 (Flow $Compose)

javascript - Twitter Web Intent 回调在 IE 中不起作用