简体   繁体   English

如何将道具传递给组件

[英]How to pass props to a component

Type '{ data: { title: string;输入'{数据:{标题:字符串; }[]; }[]; }' is not assignable to type 'IntrinsicAttributes & PropsT'. }' 不可分配给类型 'IntrinsicAttributes & PropsT'。 Property 'data' does not exist on type 'IntrinsicAttributes & PropsT'.类型“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.在这里, data是给定的道具。 It's an object.这是一个 object。 You probably meant to destructure this:你可能打算解构这个:

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

The props type PropsT should reflect this:道具类型PropsT应该反映这一点:

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

Another change was [{ title: string }] to { title: string }[] .另一个变化是[{ title: string }]{ 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.元组具有固定长度,而 arrays 可以拥有任意数量的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM