Next.js报错:类型{}不存在children属性,如何基于NextPage修正?
修复Next.js中NextPage组件children属性的类型报错
你遇到的错误是因为NextPage默认的props类型不包含children字段——NextPage是Next.js为页面组件设计的类型,页面组件通常不需要接收children,因此默认未包含该属性定义。
基于导入的NextPage类型,有两种规范的修正方式:
方式一:通过泛型参数声明children属性
- 先导入
ReactNode类型(如果尚未导入):
import { ReactNode } from "react";
- 修改
StateProvider的类型定义,给NextPage传入包含children的泛型参数:
export const StateProvider: NextPage<{ children: ReactNode }> = ({ children }) => { const [states, dispatch] = useReducer(reducer, initialState); return ( <StateContext.Provider value={{ states, dispatch }}> {children} </StateContext.Provider> ); };
方式二:通过交叉类型扩展NextPage
直接将NextPage与包含children的类型合并:
import { ReactNode } from "react"; export const StateProvider: NextPage & { children: ReactNode } = ({ children }) => { const [states, dispatch] = useReducer(reducer, initialState); return ( <StateContext.Provider value={{ states, dispatch }}> {children} </StateContext.Provider> ); };
两种方式都能解决类型报错,推荐第一种泛型参数的写法,更贴合NextPage的设计规范。
内容的提问来源于stack exchange,提问作者vinod827
相关产品推荐
相关产品推荐

