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

如何在TypeScript严格模式下将Next.js函数式MyApp转为类组件

问题解答

先搞懂你疑惑的语法

{ Component, pageProps }: AppProps 是TypeScript里对象解构+类型注解的写法:

  • 整体意思是:当前组件接收的props是一个类型为AppProps的对象,我们直接从这个对象里提取Component和pageProps两个属性来用,不用每次写props.Component、props.pageProps。
  • 你的猜测没错,这个props对象确实包含Component和pageProps字段,且整个对象的类型由Next.js提供的AppProps定义。

转换后的类组件代码

import type { AppProps } from 'next/app'
import React from 'react';
import '../styles/styles.css';

// 泛型第一个参数是props类型(即AppProps),第二个是state类型(这里不需要状态,传空对象{})
class MyApp extends React.Component<AppProps, {}> {
  render() {
    // 从this.props里解构出需要的属性
    const { Component, pageProps } = this.props;
    return <Component {...pageProps} />;
  }
}

export default MyApp;

关键点说明

  • 类组件的泛型参数规则:React.Component<PropsType, StateType>,这里props类型直接用Next.js提供的AppProps即可;因为该组件不需要内部状态,所以StateType传空对象{}。
  • 类组件中访问props必须通过this.props,所以在render方法里做解构操作,和原函数式组件的逻辑保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:50:22