Typescript中如何为Material UI自定义PopperComponent定义props类型
修复方案
你需要给CustomPopper组件的props声明正确的类型,直接复用MUI Popper组件的官方类型即可,无需手动定义:
写法1(推荐)
使用React.ComponentProps直接推导Popper组件的props类型,无需额外导入类型定义:
import React from 'react'; import { Popper } from '@mui/material'; const CustomPopper = (props: React.ComponentProps<typeof Popper>) => { return <Popper {...props} css={styles.popper} placement="bottom-start" />; };
写法2
显式导入PopperProps做类型标注:
import React from 'react'; import { Popper, PopperProps } from '@mui/material'; const CustomPopper = (props: PopperProps) => { return <Popper {...props} css={styles.popper} placement="bottom-start" />; };
两种写法效果完全一致,第一种写法无需关心组件props类型的导出路径,适配所有MUI版本,不会出现类型导入路径错误的问题。
若项目使用emotion作为css-in-js方案,且css属性仍报类型错误,可在tsconfig.json的compilerOptions中添加配置:
{ "compilerOptions": { "jsxImportSource": "@emotion/react" } }
内容的提问来源于stack exchange,提问作者meez
相关产品推荐
相关产品推荐

