简体   繁体   中英

Pass down component with props as prop in React Typescript

I'm learning React with Typescript and hit an obstacle. I'm trying to pass a child component that has props to another child component like so:

const About = () => {

  const skills: string[] = ['a', 'b', 'c', 'd', 'e', 'f']
  const columns: number = 2
  const title: string = "ABOUT"
  const text: string = `Lorem Ipsum.`

  return (
    <Card
      text={text}
      title={title}
      skillsComponent={<Skills skills={skills} columns={columns}/>}
    >
    </Card>
  );
};

and use the Skills component like so:

const Card: FC<CardProps>  = ({ title, text, skillsComponent }): JSX.Element => {

  return (
    <div>
      <div className="container">
        <div className="title">{title}</div>
        <div className="underline"></div>
        <div className="card">
          <div className="text">
            {text}
          </div>
        </div>
      </div>
      {skillsComponent}
    </div>
  )
}

{skillsComponent} gives the error Type 'Element' is not assignable to type 'FC<SkillsProps>'. Not sure what's the best solution here.

You don't need to bother with FC<CardProps> , or defining the return type since that will be inferred. Typically when you build a card component you can just use a children Prop as below.

const About = () => {

  const skills: string[] = ['a', 'b', 'c', 'd', 'e', 'f']
  const columns: number = 2
  const title: string = "ABOUT"
  const text: string = `Lorem Ipsum.`

  return (
    <Card
      text={text}
      title={title}
    ><Skills skills={skills} columns={columns}/>
    </Card>
  );
};

interface CardProps {title:string, text:string, children:React.Node}

const Card  = ({ title, text,children }:CardProps) => {
  return (
    <div>
      <div className="container">
        <div className="title">{title}</div>
        <div className="underline"></div>
        <div className="card">
          <div className="text">
            {children}
          </div>
        </div>
      </div>
    </div>
  )
}

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