首页 > 解决方案 > 使用带有附加道具的“styled()”MUI 实用程序(Typescript)

问题描述

我正在使用 Material UI v.5 开发一个新项目。我在styled()这里使用实用程序(不是 styled-components)来设计和创建简单的 UI 组件。该项目在打字稿中。我现在有很多困难,因为我不知道是否以及如何将道具传递给这些组件。例如,我有这样的组件:

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


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

我想以这种方式使用它:

return <InputField width={100}>

但它给了我一个错误:

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

所以我的问题是:我怎样才能为这种 MUI 风格的组件提供额外的道具?

标签: reactjstypescriptmaterial-ui

解决方案


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

type InputProps = {
  width: number
}

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

Codesandbox 演示


推荐阅读