简体   繁体   中英

How to pass `props` to another component in TypeScript

I have this component:

interface listvote {
  items: any[]
}


const ListVote: React.FC<listvote> = props => {
  useEffect(() => {
    console.log(items)
  })
  return (
    <VoteResult
      id={props.id}
      img={props.img}
      name={props.name}
      score={props.score}
    />
  )
}

export default ListVote

It receives this Array as a prop:

<ListVote items={dataListVote} />


const dataListVote = [
    {
      id: 1,
      img:
        'sampleimage.com',
      name: 'samplename',
      score: 50,
    },
    {
      id: 2,
      img:
        'sampleimage.com',
      name: 'samplename',
      score: 80,
    },
  ]

There is another component inside ListVote:

interface voteresult {
  items: any[]
}

const VoteResult: React.FC<voteresult> = props => {
  useEffect(() => {
    console.log(props)
  })
  return <h1>hello</h1>
}

export default VoteResult

The problem is when I try to pass the same array to another component inside ListVote component, it throws this error:

    Type 'PropsWithChildren<listvote>' is missing the following properties from type 'any[]': length, pop, push, concat, and 28 more.

Based on your usage:

<VoteResult
      id={props.id}
      img={props.img}
      name={props.name}
      score={props.score}
    />

VoteResult does not accept items as a prop. So your type is incorrect:

interface voteresult {
  items: any[]
}

Correct Type

The simplest type to get rid of the error:

interface voteresult {
  id: any;
  img: any;
  name: any;
  score: any;
}

Home component:

const dataListVote = [
    {
      id: 1,
      img:
        'sampleimage.com',
      name: 'samplename',
      score: 50,
    },
    {
      id: 2,
      img:
        'sampleimage.com',
      name: 'samplename',
      score: 80,
    },

]

<ListVote items={dataListVote} />

ListVote COmponent:

interface listvote {
  items: any[]
}

const ListVote: React.FC<listvote> = props => {
  useEffect(() => {
    console.log(typeof props)
  })
  return <VoteResult items={props} />
}

export default ListVote

VoteResult Component:

interface listvote {
  items: any[]
}


const VoteResult: React.FC<voteresult> = props => {
  useEffect(() => {
    console.log(props)
  })
  return <h1>hello</h1>
}

export default VoteResult

Error:

Type 'PropsWithChildren<listvote>' is missing the following properties from type 'any[]': length, pop, push, concat, and 28 more. 

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