TypeScript and React - children type?

前端 未结 14 1176
借酒劲吻你
借酒劲吻你 2020-12-12 18:56

I have a very simple functional component as follows:

import * as React from \'react\';

export interface AuxProps  { 
    children: React.ReactNode
 }


con         


        
相关标签:
14条回答
  • 2020-12-12 19:08

    Just children: React.ReactNode

    0 讨论(0)
  • 2020-12-12 19:08

    This is what worked for me:

    interface Props {
      children: JSX.Element[] | JSX.Element
    }
    

    Edit I would recommend using children: React.ReactNode instead now.

    0 讨论(0)
  • 2020-12-12 19:10

    The general way to find any type is by example. The beauty of typescript is that you have access to all types, so long as you have the correct @types/ files.

    To answer this myself I just thought of a component react uses that has the children prop. The first thing that came to mind? How about a <div />?

    All you need to do is open vscode and create a new .tsx file in a react project with @types/react.

    import React from 'react';
    
    export default () => (
      <div children={'test'} />
    );
    
    

    Hovering over the children prop shows you the type. And what do you know -- Its type is ReactNode (no need for ReactNode[]).

    Then if you click into the type definition it brings you straight to the definition of children coming from DOMAttributes interface.

    // node_modules/@types/react/index.d.ts
    interface DOMAttributes<T> {
      children?: ReactNode;
      ...
    }
    

    Note: This process should be used to find any unknown type! All of them are there just waiting for you to find them :)

    0 讨论(0)
  • 2020-12-12 19:15

    A React Node is one of the following types:

    • Boolean (which is ignored)
    • null or undefined (which is ignored)
    • Number
    • String
    • A React element (result of JSX)
    • An array of any of the above, possibly a nested one
    0 讨论(0)
  • 2020-12-12 19:18

    you can declare your component like this:

    const MyComponent: React.FunctionComponent = (props) => {
        return props.children;
    }
    
    0 讨论(0)
  • 2020-12-12 19:19

    React components should have a single wrapper node or return an array of nodes.

    Your <Aux>...</Aux> component has two nodes div and main.

    Try to wrap your children in a div in Aux component.

    import * as React from 'react';
    
    export interface AuxProps  { 
      children: React.ReactNode
    }
    
    const aux = (props: AuxProps) => (<div>{props.children}</div>);
    
    export default aux;
    
    0 讨论(0)
提交回复
热议问题