简体   繁体   中英

How to pass props to a component

Type '{ data: { title: string; }[]; }' is not assignable to type 'IntrinsicAttributes & PropsT'. Property 'data' does not exist on type 'IntrinsicAttributes & PropsT'.

const ParentComp = () => {
  const values = [
    { title: 'someText' }
  ]
  return <ChildComp data={values} /> // WARNING
}

type PropsT = [
  { title: string }
]
const ChildComp = (data: PropsT) => {
  return <>{data[0].title}</>
}

There's two problems:

const ChildComp = (data: PropsT) => {

Here, data is the props given. It's an object. You probably meant to destructure this:

const ChildComp = ({ data }: PropsT) => {

The props type PropsT should reflect this:

type PropsT = {
    data: { title: string; }[];
};

Another change was [{ title: string }] to { title: string }[] .

The former is a tuple with only one element, while the latter is an array. Tuples have fixed lengths while arrays can have as many elements as it wants.

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