使用带有附加道具的“styled()”MUI 系统实用程序 (Typescript)

dra*_*ski 34 typescript reactjs material-ui

我正在使用 MUI System v5 开发一个新项目。我在这里使用styled()实用程序(不是样式组件)来设计和创建简单的 UI 组件。该项目采用 TypeScript。我现在有很多困难,因为我不知道是否以及如何将道具传递给这些组件。例如,我有一个这样的组件:

import { styled } from '@mui/system';


const InputField = styled('input')(({ width }) => ({
  width: width
}));

Run Code Online (Sandbox Code Playgroud)

我想以这种方式使用它:

return <InputField width={100}>
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误:

Property 'width' does not exist on type '{ theme?: Theme; as?: ElementType<any>; sx?: SxProps<Theme>; } & ClassAttributes<HTMLDivElement> & HTMLAttributes<HTMLDivElement> & { ...; }'.ts(2339)

所以我的问题是:如何为此类 Material UI 组件提供额外的 props?

Nea*_*arl 64

您可以将泛型类型参数添加到返回的函数中,styled如下所示:

type InputProps = {
  width: number
}

const InputField = styled('input')<InputProps>(({ width }) => ({
  width: width
}));
Run Code Online (Sandbox Code Playgroud)

Codesandbox 演示