【发布时间】:2021-04-13 22:27:01
【问题描述】:
我正在尝试为我的样式化组件创建一个包装器,但我无法正确选择类型。
假设我有一个这样的样式组件:
const Button = styled.button<ButtonProps>`
background-color: ${(props) => props.color};
`;
现在我想创建一个包含此样式按钮的包装器组件,例如。像这样:
const WrappedButton: React.FunctionComponent<ButtonProps> = ({ children, ...rest }) => (
<div>
<Button {...rest}>{children}</Button>
</div>
);
现在一切正常,但我真正想要的是WrappedButton 组件接受Button 组件将接受的所有道具并将它们传递给包装的Button 组件 .
例如,我希望编译它,因为 type 是 HTML 按钮元素的有效属性(因此也是 Button 组件的有效属性,但不是在包装 Button 组件时):
// TypeScript will throw an error because "type" is not a valid prop of WrappedButton.
const MyComponent = () => <WrappedButton type="submit">Test</WrappedButton>
我知道我可以“键入” WrappedComponent 的道具,但这不是重点,我希望 WrappedComponent 接受普通 HTML 按钮可以接受的所有道具。
编辑:我还需要包装组件上的所有样式组件特定道具,例如样式组件的as 道具。这是代码沙箱的更新版本:https://codesandbox.io/s/react-typescript-styled-components-forked-3o20j?file=/src/index.tsx
我尝试了很多东西,但 TypeScript 总是在抱怨。我也搜索了文档和互联网,但没有找到任何东西。
【问题讨论】:
标签: reactjs typescript styled-components