javascript - 将 Flow 用于样式化组件 Props

标签 javascript reactjs types flowtype styled-components

所以我一直在研究 JavaScript 中的类型系统,大部分情况下一切正常,但是样式组件存在问题。我似乎找不到将流程应用于样式化组件的 Prop 的好方法。到目前为止,我看到的唯一解决方案是:

export type ButtonPropTypes = ReactPropTypes & {
  styleType: 'safe' | 'info' | 'warning' | 'danger' | 'link',
  isPill: boolean,
  isThin: boolean,
};

export const ButtonStyled = styled.button`
  ${generateBaseStyles}
  ${hoverStyles}
  ${fillStyles}
  ${thinStyles}
  ${linkStyles}
`;

export const Button = (props: ButtonPropTypes) => <ButtonStyled {...props} />;

我必须为每个样式组件创建 2 个组件,这似乎太过分了。

我希望我的 google 技能只是废话,我遗漏了一些东西,但是除了每个样式组件多个组件之外,还有更好的方法吗?

最佳答案

是的!有一个更好的办法。诀窍是声明由 styled-components 创建的组件的类型。你可以通过casting来做到这一点styled.button`...` 返回的结果到接收所需 Prop 的 React 组件的类型。您可以使用 type mytype = React.ComponentType<MyProps> 生成接受任意 Prop 的 React 组件类型。 .

// @flow
import styled from 'styled-components'
// Make sure you import with * to import the types too
import * as React from 'react'

// Mock function to use styleType
const makeStyles = ({styleType}) => ''

export type ButtonPropTypes = {
  styleType: 'safe' | 'info' | 'warning' | 'danger' | 'link',
  isPill: boolean,
  isThin: boolean,
};

export const ButtonStyled = (styled.button`
  ${makeStyles}
  ${({isPill}) => isPill ? 'display: block;' : ''}
  ${({isThin}) => isThin ? 'height: 10px;' : 'height: 100px;'}
`: React.ComponentType<ButtonPropTypes>) // Here's the cast

const CorrectUsage = <ButtonStyled styleType="safe" isPill isThin/>

const CausesError = <ButtonStyled styleType="oops" isPill isThin/> // error

const CausesError2 = <ButtonStyled styleType="safe" isPill="abc" isThin={123}/> // error

我已将代码托管在 GitHub 上以进行本地复制(因为 Flow 的沙箱不适用于外部依赖项):https://github.com/jameskraus/flow-example-of-styled-components-props

关于javascript - 将 Flow 用于样式化组件 Props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49041401/

相关文章:

language-agnostic - 弱类型相对于强类型的优势

javascript - 将代码分配给特定按钮

javascript - 在 ReactJS 中将新的子 DOM 追加到父级中时面临的问题

javascript - 如何向表添加键

scala - 如何在scala中设置类型参数绑定(bind)来为数字创建泛型函数?

objective-c - int 和 NSInteger 有什么区别?

javascript - Angular js ng-click 在子元素中不起作用

php - 如何创建安全的 php 和 javascript api

javascript - 访问不存在的图像 URL 是否会影响 Web 服务器?

javascript - React JS 粘性导航 onScroll