React+TypeScript+Material UI自定义组件编译报错求助
React+TypeScript组件导入错误:原因与解决方法
问题场景
开发基于TypeScript和Material UI的React应用时,自定义组件tempSelector无法被正确识别,运行出现编译错误。相关代码及错误信息如下:
tempSelector.tsx代码
import {Autocomplete, TextField} from "@mui/material"; const theData = [ { info: 'Hello', name: 'Info data', }, { info: 'World', name: 'More data', }, { info: 'HowAreYou', name: 'Still More Data', }, ]; const tempSelector = () => { return( <Autocomplete disablePortal options={theData} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Movie" />} /> ) } export default { tempSelector }
App.tsx代码
import './App.css' import tempSelector from "./tempSelector.tsx"; function App() { return ( <> <tempSelector /> </> ) } export default App
编译错误信息
TS6133: 'tempSelector' is declared but its value is never read. ESLint: 'tempSelector' is defined but never used. (@typescript-eslint/no-unused-vars) TS2339: Property 'tempSelector' does not exist on type 'JSX.IntrinsicElements'.
错误原因
- 导出方式错误:
tempSelector.tsx中通过export default { tempSelector }导出的是一个包裹组件的对象,而非组件函数本身。App.tsx导入后拿到的是这个对象,不是可直接渲染的组件。 - 组件命名不符合规范:React要求组件名必须大写开头,小写开头的标识符会被TypeScript识别为原生HTML标签(属于
JSX.IntrinsicElements),无法被识别为自定义组件。 - 导入后未正确使用:因为导入的是对象,实际组件是
tempSelector.tempSelector,但代码中直接用<tempSelector />,导致导入的对象未被真正使用,触发未使用变量的提示。
解决方法
方案一:修正默认导出与组件命名
修改tempSelector.tsx,直接导出组件函数为默认导出,并将组件名改为大写开头:
import {Autocomplete, TextField} from "@mui/material"; const theData = [ { info: 'Hello', name: 'Info data', }, { info: 'World', name: 'More data', }, { info: 'HowAreYou', name: 'Still More Data', }, ]; // 组件名改为大写开头 const TempSelector = () => { return( <Autocomplete disablePortal options={theData} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Movie" />} /> ) } // 直接导出组件函数,而非包裹对象 export default TempSelector
修改App.tsx,正确导入并使用大写开头的组件:
import './App.css' // 导入大写开头的组件 import TempSelector from "./tempSelector.tsx"; function App() { return ( <> <TempSelector /> </> ) } export default App
方案二:使用命名导出
如果倾向于命名导出,修改tempSelector.tsx:
import {Autocomplete, TextField} from "@mui/material"; const theData = [ { info: 'Hello', name: 'Info data', }, { info: 'World', name: 'More data', }, { info: 'HowAreYou', name: 'Still More Data', }, ]; // 大写开头的组件名 + 命名导出 export const TempSelector = () => { return( <Autocomplete disablePortal options={theData} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Movie" />} /> ) }
修改App.tsx,使用命名导入:
import './App.css' // 命名导入组件 import { TempSelector } from "./tempSelector.tsx"; function App() { return ( <> <TempSelector /> </> ) } export default App
总结
核心问题是导出方式错误和组件命名不符合React规范,导致TypeScript无法识别组件类型,同时触发未使用变量的提示。修正后即可正常渲染组件。
内容的提问来源于stack exchange,提问作者Factor Three
相关产品推荐
相关产品推荐

