reactjs - typescript 将样式化的组件 Prop 与父级 Prop 合并

标签 reactjs typescript styled-components

我有一个看起来像这样的样式组件:

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<"div", any, BoxProps, never>React.FC<ContainerProps> :

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

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

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

谢谢!

最佳答案

styled.div只呈现 div它接受任何属性 div会接受来自 BoxProps 的 + 您的属性.您可以使用 React.HTMLAttributes<HTMLElementYouNeed> 获取描述 JSX 元素属性的类型在这种情况下 React.HTMLAttributes<HTMLDivElement> , 所以 Box 的 Prop 现在是这个加上 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>

关于reactjs - typescript 将样式化的组件 Prop 与父级 Prop 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64943557/

相关文章:

javascript - styled-components:扩展样式和改变元素类型

javascript - 检查颜色是否为字符串 ('white' === color?//true, 'bright white gold' === color?//false)

routes - 登录后将用户重定向到预期的 url Reactjs

typescript - Mocha & Typescript 和递归加载

angular - 需要帮助正确输入函数参数

javascript - React 测试库 + Jest : How to test a component that receives a number then format it

reactjs - 将样式组件与语义 UI react 一起使用时出现警告 : Prop `className` did not match.

reactjs - React Native 在打开时刷新一个组件

javascript - 如何在具有空数组的 React 组件中定义 .map 列表?

reactjs - 如何在 Material-UI 中扩展 OverridableComponent 接口(interface)