简体   繁体   中英

NextJs and Typescript passing values to parent

I've made a component

        <ConnectWallet setConnected={(t: boolean) => console.log(t)}>
          <>test</>
        </ConnectWallet>

The component starts like

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) => {
...

Error on the parent is

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)

Error on the child is

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.

If you want to reuse ConnectWallet between 2 different pages, I'd extract it to a separate component. Right now, you're trying to render one page inside of, presumably, another.

To fix the immediate issue you have, try to change:

const ConnectWallet: React.FC<PropsShape> = ({ setConnected, children }) => {

Also, you don't have to define children inside of PropsShapre

Pass the props type to NextPage :

const ConnectWallet: NextPage<PropsShape> = ({ setConnected, children }) => {

But should this really be a page if it's a child component?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM