簡體   English   中英

自定義 Next.js App 組件中未繼承 React 道具

[英]React props are not inherited in Custom Next.js App component

我創建了自定義 next.js App組件作為一個類(意圖通過初始化 Google 分析來覆蓋componentDidMount function)。

class MyApp extends App {
    async componentDidMount(): Promise<void> {
        await initializeAnalytics();
    }

    render() {
        const {Component, pageProps} = this.props;

        return (
            <Container>
                <Component {...pageProps} />
            </Container>
        );
    }
};

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "lib": ["es5", "es2015.promise", "dom"],
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "strictNullChecks": true,
        "suppressImplicitAnyIndexErrors": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "jsx": "react",
        "baseUrl": ".",
        "skipLibCheck": true,
        "paths": {
            "@myapp/*": ["./node_modules"]
       }
   }
}

我面臨的問題是error TS2339: Property 'props' does not exist on type MyApp

props字段應從定義為的App組件繼承:

export default class App<P = {}, CP = {}, S = {}> extends React.Component<P & AppProps<CP>, 
S> {
    static origGetInitialProps: typeof appGetInitialProps;
    static getInitialProps: typeof appGetInitialProps;
    componentDidCatch(error: Error, _errorInfo: ErrorInfo): void;
    render(): JSX.Element;
}

為什么編譯器會抱怨MyApp組件上缺少props字段? 它不應該從擴展React.ComponentApp組件繼承嗎?

使用的版本:

  • Typescript 4
  • Next.js 10.0.0
  • 反應 17.0.0
  • @types/反應 17.0.0

您需要在tsconfig.json文件的compilerOptions下添加"esModuleInterop": true

我還建議你使用"jsx": "preserve"來避免其他與 React 相關的問題。

為了讓你使用this.props ,props 應該是 myApp class 中的一個方法。 因此this.props不存在編譯器發出的信號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM