You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 12:03:20