TypeScript 3: JSX element type 'Component' does not have any construct or call signatures. [2604]

后端 未结 5 740
挽巷
挽巷 2021-02-07 10:06

I\'m trying to pass a variable of type React.Component (or React.FunctionComponent) into a Route, like this:

import React from \'react\';
import { Route } from \         


        
5条回答
  •  礼貌的吻别
    2021-02-07 10:19

    This is late but in case someone didn't want a solution but an explanation, let's talk about this error using an example to demonstrate it

    function PaymentPage(){
      
       return 
    Payment Page
    }

    say we want to create a dynamic payment form, if the query parameter is with=stripe so we assume he wants to pay with stripe, if it's with razorpay we assume it, ...etc.

    we then do something like

    function PaymentPage(){
       const router = useRouter;
       const {with} = router.query;
       let GatewayComponent: Gateway | null = null;
       switch(with){
         case 'stripe':
           return 
         case 'razorpay':
           return 
       }
       return 
    }
    

    Running this, we get

    JSX element type 'Component' does not have any construct or call signatures.
    

    What happens?

    What are component?

    • Constructors that return elements of type JSX.Element

    So?

    • We are not returning a constructor, we are returning a Constructor call, it's the same as assuming that GatewayComponent is a constructor, but it's not, it's a variable holding JSX

    So basically, expects x to be a constructor of any type, either a function or a class, if it's a function, the function is the render function, if it's a class, it needs a render method.

    Back to our problem

    function PaymentPage(){
       const router = useRouter;
       const {with} = router.query;
       let gateway: Gateway | null = null;
       switch(with){
         case 'stripe':
           return 
         case 'razorpay':
           return 
       }
       return  {gateway} 
    }
    

    Because gateway holds JSX, not a constructor that returns JSX

    What if you want to use it as a component?

    function PaymentPage(){
       const router = useRouter;
       const {with} = router.query;
       let GatewayComponent: Gateway | null = null;
       switch(with){
         case 'stripe':
           return () => 
         case 'razorpay':
           return () => 
       }
       return 
    }
    

    Now it's a constructor, we can use it as a component right now.

    Formally, you pass the constructor and not the instance.

提交回复
热议问题