样式的组件隐藏了Typescript中的HTML属性

发布于 2025-02-01 03:43:40 字数 308 浏览 1 评论 0原文

我创建了一个标准样式组件,例如:

export type ContainerProps = {
  color: string;
};

export const Container = styled.div<ContainerProps>`
  color: ${p => p.color};
  background: blue;
  width: 100%
`;

当我想在JSX中使用此组件时,我具有所有HTML属性作为Props。

有什么方法可以限制这些方法,以便用户只能使用道具类型中指定的道具?

I create a standard Styled Component like:

export type ContainerProps = {
  color: string;
};

export const Container = styled.div<ContainerProps>`
  color: ${p => p.color};
  background: blue;
  width: 100%
`;

When I want to use this component in JSX I have all the HTML attributes available as props.

Is there any way how to restrict these, so that the user can use only props specified in props type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梓梦 2025-02-08 03:43:40

我怀疑您是否可以实现它,请检查实现在这里

可以创建另一个组件并导出此组件。

export const StyledContainer = styled.div<ContainerProps>`
  color: ${(p) => p.color};
  background: blue;
  width: 100%
`;

export const Container: FC<ContainerProps> = (...props) => (
  <StyledContainer {...props} />
);

SC添加了额外的默认HTML Props(OnClick,Onblur等),如果我们提供FC,它将仅接受类型的道具。

export type ContainerProps = {
  color: string,
};
export const Container: FC<ContainerProps> = styled.div<ContainerProps>`
  color: ${(p) => p.color};
  background: blue;
  width: 100%
`;

I doubt you will be able to achieve it, check the implementation here

A naive approach can be, to create another component and export this.

export const StyledContainer = styled.div<ContainerProps>`
  color: ${(p) => p.color};
  background: blue;
  width: 100%
`;

export const Container: FC<ContainerProps> = (...props) => (
  <StyledContainer {...props} />
);

SC adds extra default HTML props(onClick, onBlur etc), If we provide FC it'll only accept Type props.

export type ContainerProps = {
  color: string,
};
export const Container: FC<ContainerProps> = styled.div<ContainerProps>`
  color: ${(p) => p.color};
  background: blue;
  width: 100%
`;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文