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

如何传递组件作为参数?TypeScript下React路由类型报错解决

解决TypeScript路由类型报错问题

错误原因分析

报错提示'Quiz' refers to a value, but is being used as a type here,常见触发原因有两个:

  • 组件导入方式错误,误用了类型导入(import type)导致Quiz仅为类型标识,而非实际可渲染的组件值;
  • 路由接口中component的类型定义不符合React组件的类型规范。

解决方案

方案1:修正组件导入方式

如果你的Quiz组件导入时用了import type,请改为普通导入:

// 错误写法
// import type { Quiz } from './Quiz';

// 正确写法(默认导出)
import Quiz from './Quiz';

// 或(命名导出)
import { Quiz } from './Quiz';

方案2:修正路由接口的component类型

根据你的路由使用场景,分两种情况调整类型:

情况A:直接传递组件本身(推荐,符合React Router等路由库常规用法)

将component类型定义为React官方提供的ComponentType,它兼容函数组件和类组件:

import React from 'react';
import Quiz from './Quiz';

interface IRoute {
    name: string;
    path: string;
    component: React.ComponentType; // 使用ComponentType
}

const routes: IRoute[] = [
    { name: 'Quiz', path: '/quiz', component: Quiz }, // 直接传入组件
];

export default routes;

情况B:保持返回JSX的函数形式

如果你的路由逻辑需要component是一个返回JSX元素的函数,需将类型修正为() => React.ReactElement(ReactNode范围过宽,包含非JSX类型,易导致类型不匹配):

import React from 'react';
import Quiz from './Quiz';

interface IRoute {
    name: string;
    path: string;
    component: () => React.ReactElement; // 明确返回ReactElement
}

const routes: IRoute[] = [
    { name: 'Quiz', path: '/quiz', component: () => <Quiz /> },
];

export default routes;

内容的提问来源于stack exchange,提问作者fsgdoterr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:25:25