React、样式组件和 TypeScript:如何将样式组件包装在功能组件中

omn*_*ain 6 typescript reactjs styled-components

我正在尝试为我的样式组件创建一个包装器,但我无法正确获取类型。

假设我有一个这样的样式组件:

const Button = styled.button<ButtonProps>`
  background-color: ${(props) => props.color};
`;

Run Code Online (Sandbox Code Playgroud)

现在我想创建一个包含此样式按钮的包装组件,例如。像这样:

const WrappedButton: React.FunctionComponent<ButtonProps> = ({ children, ...rest }) => (
  <div>
    <Button {...rest}>{children}</Button>
  </div>
);

Run Code Online (Sandbox Code Playgroud)

现在这一切都工作正常,但我真正想要的是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>

Run Code Online (Sandbox Code Playgroud)

我知道我可以将“type”作为 WrappedComponent 的 props,但这不是重点,我希望 WrappedComponent接受普通 HTML 按钮会接受的所有 props

编辑:我还需要包装组件上的所有样式组件特定道具,例如as样式组件的道具。这是代码沙箱的更新版本:https://codesandbox.io/s/react-typescript-styled-components-forked-3o20j ?file=/src/index.tsx

我已经尝试了很多东西,但 TypeScript 总是抱怨。我还搜索了文档和互联网,但没有找到任何东西。

cap*_*ian 2

我相信你问的是React.ButtonHTMLAttributes<HTMLButtonElement>

import React from 'react'
import styled from 'styled-components'

const Button = styled.button<ButtonProps>`
  background-color: ${(props) => props.color};
`;


type ButtonProps = {
} & React.ButtonHTMLAttributes<HTMLButtonElement>;


const WrappedButton: React.FunctionComponent<ButtonProps> = ({ children, ...rest }) => (
    <div>
        <Button {...rest}>{children}</Button>
    </div>
);

Run Code Online (Sandbox Code Playgroud)

如果您想使用原始 html <button>,您可能会对:JSX.IntrinsicElements["button"];

检查这个答案

更新 快速而肮脏的解决方案是:

type ButtonProps = {
} & React.ButtonHTMLAttributes<HTMLButtonElement> & { as?: string | React.ComponentType<any> };
Run Code Online (Sandbox Code Playgroud)

但它不是通用的。

SC 类型中有StyledComponentPropsWithAs类型,但未导出(