【问题标题】:Typescript merging styled component props with the parent ones打字稿将样式化的组件道具与父组件合并
【发布时间】:2021-03-04 16:49:09
【问题描述】:

我有一个样式组件,如下所示:

interface BoxProps {
    color?: string;
    backgroundColor?: string;
    borderColor?: string;
  }

export const Box = styled.div<BoxProps>`
  position: relative;
  padding: 0.75rem 1.25rem;
  margin-bottom: 1rem;
  border: 1px solid transparent;
  border-radius: 0.25rem;
  text-align: left;
  color: ${(props) => props.color};
  background-color: ${(props) => props.backgroundColor};
  border-color: ${(props) => props.borderColor};
`;

它被包裹在另一个组件中:

export const Container: React.FC<ContainerProps> = ({
  variant,
  children,
  ...props
}) => {
  const { color, backgroundColor, borderColor } = variantColor(variant);

  return (
    <div>
      <Box
        color={color}
        backgroundColor={backgroundColor}
        borderColor={borderColor}
        {...props}
      >
        {children}
      </Box>
      <p></p>
      // ...
    </div>
  );
};

如果我将StyledComponent&lt;"div", any, BoxProps, never&gt; 添加到React.FC&lt;ContainerProps&gt;

React.FC<ContainerProps & StyledComponent<"div", any, BoxProps, never>>

传播道具会给我以下错误: Rest types may only be created from object types 我试过React.HTMLAttributes&lt;{}&gt; &amp; typeof Box.propTypesReact.DetailedHTMLProps&lt;React.HTMLAttributes&lt;HTMLDivElement&gt;, HTMLDivElement&gt; 没有运气...

有没有办法将样式组件道具与父道具合并?

谢谢!

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    styled.div 只呈现一个div,它接受div 将接受的任何属性+来自BoxProps 的属性。您可以使用React.HTMLAttributes&lt;HTMLElementYouNeed&gt; 获得描述JSX 元素属性的类型,在这种情况下为React.HTMLAttributes&lt;HTMLDivElement&gt;,所以Box 的props 现在是这个加上BoxProps

    React.FC<ContainerProps & React.HTMLAttributes<HTMLDivElement> & BoxProps>
    

    如果你懒得写这个,你可以在项目的某个文件中创建一个实用程序命名空间:

    declare namespace HTMLProps {
      type div = React.HTMLAttributes<HTMLDivProps>
      // Maybe define props for other html elements if you need
    }
    export default HTMLProps
    

    然后导入这个并使用

    React.FC<ContainerProps & HTMLProps.div & BoxProps>
    

    【讨论】:

      【解决方案2】:

      Alex 的回答是有效的,但在某些情况下它不起作用。例如我有这个样式的组件:

      export const CustomInput = styled.input.attrs({ type: 'text' })``;
      

      使用:

      React.HTMLAttributes<HTMLInputElement>
      // or
      Omit<React.HTMLAttributes<HTMLInputElement>,'type'>
      

      在父组件中给出错误。

      为此,您需要:

      Omit<React.ComponentPropsWithoutRef<'input'>, 'type'>
      

      【讨论】:

        猜你喜欢
        • 2021-06-07
        • 2020-06-03
        • 2021-07-11
        • 2020-11-02
        • 2020-06-27
        • 2021-05-02
        • 2020-08-02
        • 2019-10-01
        • 2022-01-18
        相关资源
        最近更新 更多