【问题标题】:How to pass data in reactjs using typescript如何使用打字稿在reactjs中传递数据
【发布时间】:2019-12-12 09:43:43
【问题描述】:

如何使用 tsx 将对象传递给 reactjs 中的子组件。当我尝试这种方式时,我收到了这个错误。我可以在哪里声明类型? Property 'value' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<ShipmentCard>

Cards.tsx

  render() {
    return (
      <div>
        {this.state.card.map((card: any) => (
          <ShipmentCard key={card.id} value={card}/>
        ))}
      </div>
    );
  }

完整的错误信息是:

键入'{键:任意;数据:任何; }' 不可分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly'。属性“数据” 'IntrinsicAttributes & 类型不存在 IntrinsicClassAttributes & Readonly & Readonly'

【问题讨论】:

  • 完整错误信息Type '{ key: any; data: any; }' is not assignable to type 'IntrinsicAttributes &amp; IntrinsicClassAttributes&lt;ShipmentCard&gt; &amp; Readonly&lt;{}&gt; &amp; Readonly&lt;{ children?: ReactNode; }&gt;'. Property 'data' does not exist on type 'IntrinsicAttributes &amp; IntrinsicClassAttributes&lt;ShipmentCard&gt; &amp; Readonly&lt;{}&gt; &amp; Readonly&lt;{ children?: ReactNode; }&gt;'

标签: reactjs components pass-data tsx


【解决方案1】:

如果您使用的是 typescript,那么您必须在 ShipmentCard.tsx 中声明所有道具

interface ShipmentCardProps {
    key: string;
    value: {}
}

interface ShipmentCardState {}

class ShipmentCard extends React.Component<ShipmentCardProps, ShipmentCardState> {
}
export default ShipmentCard

【讨论】:

  • @SKL 能帮上忙真是太好了
【解决方案2】:

试试this。你在你的州有“卡”吗?好像没有。您需要从父组件获取道具。您需要尝试使用道具传递数据。所以阅读链接。并尝试使用 redux。

【讨论】:

  • 是的,我做到了。当render() 中的console.log this.props 显示空对象。 tsx 检查类型这就是抛出此错误的原因
  • 对象为空两次?在安装过程中,它可能是空的。更新后发生了什么(第二次渲染)
  • 如果你在value 属性中传递一个对象,它会抛出一个错误但值仍然显示控制台日志。错误Property 'value' does not exist on type 'IntrinsicAttributes &amp; IntrinsicClassAttributes&lt;ShipmentCard&gt; &amp; Readonly&lt;{}&gt; &amp; Readonly&lt;{ children?: ReactNode; }&gt;'如果我们修复类型将修复此问题
  • stackoverflow.com/questions/48240449/… 我找到了这个答案。它说:“使用 typescript 时必须提供 propTypes 和 stateType。”
猜你喜欢
  • 2018-05-15
  • 2023-01-12
  • 2022-11-26
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多