React - Type {children: Element} has no properties in common with type Intrinsic

1,043 阅读1分钟

image.png

写了一行代码想加个children 提示 类型"{ children: string; }"和类型'IntrinsicAttributes'没有共同的属性

第一种解决办法 不带children

class App extends React.Component {
   render (){
     return(
       <div>
         <ListItem />
       </div>
     )
   }
}

第二种解决办法 声明一个children

import React from "react"

type ListItemProps = {
  children: React.ReactNode; // 👈️ type children
};

const ListItem = (props: ListItemProps) => {
  return <div>{props.children}</div>;
};

class App extends React.Component {
   render (){
     return(
       <div>
         <ListItem> 
           this is ListItem
         </ListItem>
       </div>
     )
   }
}

export default App

image.png

或者定义可以传入任何类型

import React from "react"

const ListItem = (props: any) => {
  return <div>{props.children}</div>;
};

class App extends React.Component {
   render (){
     return(
       <div>
         <ListItem> 
           this is ListItem
         </ListItem>
       </div>
     )
   }
}

export default App