如何在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
相关产品推荐
相关产品推荐

