所以我一直在研究 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/