使用流类型将子组件添加到样式化组件

时间:2018-09-16 22:06:59

标签: reactjs flowtype styled-components

我想将子组件添加到样式组件中,类似于参考文献here

是这样的:

Text = styled.div`
  ${({color}) => color && `color: ${colors[color]};`}
`

Text.H1 = Text.withComponent('h1');
...

我要抓住的是我要使用流类型来做到这一点。

到目前为止,我在这里:

import * as React from 'react';
import styled, {css, withTheme} from 'styled-components';
import type {ReactComponentFunctional, Theme, ReactComponentStyled} from 'styled-components';

type Props = {
  color?: "blue" | "green"
};

const Text = ReactComponentStyled<*> & SubComponents<*> = styled.div`
  ${({color}) => color && `color: ${colors[color]};`}
`

Text.H1 = Text.withComponent('h1');

类型错误发生在const Text

Cannot assign template string to Text because:
 • all branches are incompatible:
    • Either property H1 is missing in $npm$styledComponents$ReactComponentStyledStaticPropsWithComponent [1] but
      exists in SubComponents [2].
    • Or property H1 is missing in object type [3] but exists in SubComponents [2].
    • Or property H1 is missing in React.StatelessFunctionalComponent [4] but exists in SubComponents [2].
    • Or property H1 is missing in statics of $npm$styledComponents$ReactComponent [5] but exists in
      SubComponents [2].

     src/component/base/Text/Text.js
     43│   Caption?: ReactComponentFunctional<P & {theme: Theme}>,
     44│ };
     45│
 [2] 46│ const Text: ReactComponentStyled<*> & SubComponents<*> = styled.div`
     47│   ${({color}) => color && `color: ${colors[color]};`}
     65│ `;
     66│
     67│ Text.H1 = Text.withComponent('h1');
     68│ Text.H2 = Text.withComponent('h2');

     flow-typed/npm/styled-components_v3.x.x.js
 [3] 13│   & { defaultProps: DefaultProps }
 [4] 14│   & $npm$styledComponents$ReactComponentFunctionalUndefinedDefaultProps<Props>
       :
 [5] 23│ type $npm$styledComponents$ReactComponentClass<Props, DefaultProps = *> = Class<$npm$styledComponents$ReactComponent<Props, DefaultProps>>
       :
 [1] 70│   & $npm$styledComponents$ReactComponentStyledStaticPropsWithComponent<Props, ComponentList>

在创建Text的那一刻,它丢失了H1,但是我已经将该类型设为可选,所以我认为它应该可以工作。我也不明白为什么会出错:H1 is missing in XXX but exists in SubComponents。确实的确如此,但是我将SubComponents与样式化的组件类型相交,所以我希望这是使其有效的原因。

弄清楚这一点之后,我想更进一步,并向子组件添加默认道具和主题。

Text.H1 = withTheme((props) => {
  const Component = Text.withComponent('h1');
  Component.defaultProps = {
    color: props.theme.heading,
    size: 'xxLarge',
    weight: 'medium',
  };
  return <Component {...props} />;
});

样式组件3 流量:0.70 反应16

注意:我知道样式组件4已发布,带有添加的as属性(它代替了withComponent),但是版本4当前没有可使用的libdef文件。它也在beta中。

0 个答案:

没有答案