[英]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.Component
的App
組件繼承嗎?
使用的版本:
您需要在tsconfig.json
文件的compilerOptions
下添加"esModuleInterop": true
。
我還建議你使用"jsx": "preserve"
來避免其他與 React 相關的問題。
為了讓你使用this.props
,props 應該是 myApp class 中的一個方法。 因此this.props
不存在編譯器發出的信號
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.