首页 > 解决方案 > props 使用 styled-components 作为 html 元素中的属性可见

问题描述

样式组件的高度宽度关键字是什么?

VSpace.tsx

type VSpaceProps = { readonly height?: string; };

export const VSpace = styled.div`
  height: ${({ height }: VSpaceProps) => height};
  width: 100%;
`;

VSpace.defaultProps = { height: '.5rem' };

索引.tsx:

function App() {
  return (
    <VSpace height="0.4rem" />
  );
}

输出:

<div height="0.4rem" class="VSpace-sc-18gziyv-1 kkKpPd"></div>

标签: reactjsstyled-components

解决方案


不,height是可见的,因为它是 JSX 属性之一,它与样式组件无关。

// height is a JSX.attribute type of div element
function App() {
  return (
    <div height="0.4rem" />
  );
}

您可以检查其 TS 类型:

Type '{ height: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.

请参阅JSX 深入了解。


推荐阅读