TypeScript:React项目中如何从单个文件导入多个类?
解决方法
1. 给Page1.tsx里的两个类添加导出标识
直接在两个类定义前加上export关键字,使用命名导出的方式,就能同时导出多个类:
import React from 'react'; export class PageParams { constructor() { } } // 注意:React类组件必须继承React.Component才能正常渲染 export class Page1 extends React.Component<any> { constructor(props: any) { super(props); // 类组件的构造函数必须调用super传递props } render() { return <div>Hello</div>; } }
2. 在App.tsx中同时导入并使用两个类
用解构语法一次性导入需要的类,之后就能直接实例化或渲染它们:
import React from 'react'; import { PageParams, Page1 } from './pages/Page1'; function App() { // 实例化PageParams类 const pageParams = new PageParams(); return ( <div className="App"> {/* 渲染Page1组件 */} <Page1 /> </div> ); } export default App;
额外提示
- 命名导出支持同时导出任意多个模块成员,每个成员都以自身名称作为标识。
- 如果导入时需要给类重命名,使用
as关键字即可,比如:import { PageParams as MyParams } from './pages/Page1'。 - 你原始代码中的
Page1类没有继承React.Component,这会导致它无法作为React组件正常工作,因此必须补上继承逻辑和super(props)的调用。
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

