简体   繁体   中英

Typescript react children with type specified in function directly instead of using an interface

Why does this work:

interface UserSidebarProps {
  children? : React.ReactNode
}

function UserSidebar({children}: UserSidebarProps) {
  return (
    <div>
      {children}
    </div>
  )
}

But this does not

function UserSidebar(children?: React.ReactNode) {
  return (
    <div>
      {children}
    </div>
  )
}
// Usage
<UserSidebar>hello world</UserSidebar>

When trying to use it, the second option gives an error in vscode of:

Type '{ children: Element | null; }' is not assignable to type 'IntrinsicAttributes & ReactNode'.
  Type '{ children: Element | null; }' is missing the following properties from type 'ReactPortal': key, type, props

I would have thought these two definitions are completely equivalent, how are they different and what am I doing wrong?

What happens is that when creating a component, the props definition (the parameter of your function) should be of a class where its properties represents the props of your component. Practically, this means that on the second example you should do something like:

function UserSidebar({children}: {children?: React.ReactNode}) {
  return (
    <div>
      {children}
    </div>
   )
}

Or you could use the PropsWithChildren class like this:

function UserSidebar({children}: PropsWithChildren) {
  return (
    <div>
      {children}
    </div>
   )
}

The problem is not using an interface or not, the problem is that you changed the signature of the function (the arguments it accepts). If I remove the Typescript, can you see the difference?

function UserSidebar({children}) {

function UserSidebar(children) {

React passes props to components, and you have said that your component DOES NOT accept props, only a ReactNode .

Try adding the brace brackets again.

function UserSidebar({children}: React.ReactNode) {

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