![](/img/trans.png)
[英]Passing {children} to layout component in NextJS & Typescript
[英]NextJs and Typescript passing values to parent
我做了一個組件
<ConnectWallet setConnected={(t: boolean) => console.log(t)}>
<>test</>
</ConnectWallet>
該組件開始像
import { useState, useEffect } from 'react';
import type { NextPage } from 'next';
declare global {
interface Window {
ethereum: any;
}
}
export interface PropsShape {
setConnected: (t: boolean) => void;
children: ReactNode;
}
const ConnectWallet: NextPage = ({ setConnected, children }: PropsShape) => {
...
父母的錯誤是
Type '{ children: Element; setConnected: (t: boolean) => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
Property 'setConnected' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)
孩子的錯誤是
Type '({ setConnected, children }: PropsShape) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
Type '({ setConnected, children }: PropsShape) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
Type '({ setConnected, children }: PropsShape) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
Types of parameters '__0' and 'props' are incompatible.
Property 'setConnected' is missing in type '{ children?: ReactNode; }' but required in type 'PropsShape'.ts(2322)
ConnectWallet.tsx(13, 3): 'setConnected' is declared here.
如果您想在兩個不同的頁面之間重復使用ConnectWallet
,我會將其提取到一個單獨的組件中。 現在,您正試圖在可能是另一個頁面內呈現一個頁面。
要解決您遇到的直接問題,請嘗試更改:
const ConnectWallet: React.FC<PropsShape> = ({ setConnected, children }) => {
此外,您不必在PropsShapre
中定義children
項
將道具類型傳遞給NextPage
:
const ConnectWallet: NextPage<PropsShape> = ({ setConnected, children }) => {
但如果它是一個子組件,它真的應該是一個頁面嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.