【问题标题】:Not assignable to type IntrinsicAttributes & IntrinsicClassAttributes React.js不可分配给类型 IntrinsicAttributes & IntrinsicClassAttributes React.js
【发布时间】:2020-05-15 02:36:03
【问题描述】:

我已经与react.js 合作了一段时间。最近,我开始看到如下错误:

Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes'

我不知道发生了什么。我用谷歌搜索了一下,发现其他人说的是props 的问题。这是我看到的一个场景。而不是:

<MyComponent action={this.state.action} />

下面的工作没问题:

<MyComponent {...props} />

我想了解react中的IntrinsicAttributesIntrinsicClassAttributes是什么。您能否详细回答一下为什么会发生这种类型的错误以及这些错误到底是什么?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    IntrinsicAttributes 和 IntrinsicClassAttributes

    接口在 TypeScript 中实现。它们影响 React.jsxDOM 元素的交互,同时使用 自定义组件


    基本原则

    假设你有

    interface BarProps {
      foo: string;
    }
    
    class Bar extends React.Component<BarProps> {
      ...
    }
    

    如果你尝试渲染它

    render() {
      return (
        <form>
          <Bar />
        </form>
      );
    }
    

    你会得到一个类似的错误;因为你违反了接口类型检查。 组件应该有一个强制性的道具,即BarProps在这里作为参数传递。

    为了让它工作,你需要做一些类似的事情..

    render() {
      return (
        <form>
          <Bar foo="Jack Daniel's"/>
        </form>
      );
    }
    

    或者您可以将其从组件定义本身中删除。

    class Bar extends React.Component<> {
     ...
    }
    

    或将foo 设为可选..

    interface BarProps{
      foo?: string;
    }
    

    想法是实现一致性。

    在您的情况下,您传递了一个未知的道具,即action,它可能尚未在您的组件中定义。

    当你像&lt;MyComponent {...props} /&gt; 这样调用你的组件时——它本质上意味着,导入所有可用的道具。

    当你像 &lt;MyComponent action={this.state.action} /&gt; 这样显式调用 action 属性时,它会引发大错误。


    上面提到的错误非常臭名昭著。您可以在 debugging guide 中找到更多关于 React 和 TypeScript 的见解,其中会突出显示这些错误并分享可能的修复方法。

    您可以在此repository 中阅读有关IntrinsicAttributesIntrinsicClassAttributes 实现的更多信息

    【讨论】:

      【解决方案2】:

      挖掘 Typescript 的 checker.ts 可能会起作用,因为不需要执行对 intrinsicAttributes 进行分配的块,因为没有显式的 JsxAttributes 来比较该组件的调用(isComparingJsxAttributes 可能为假)。如果你真的需要找出是否是这种情况,请尝试调试 Typescript 的源代码。

      举个例子 这里 typescript 期望好的东西被传递,只有在组件挂载时才被解构。

      <MyComponent {...props} />
      

      但是这里 typescript 将 this.state.action 视为未定义或可能为 null,因为它永远不确定是否会传递有效值。

      <MyComponent action={this.state.action} />
      

      即使你有正确的动作道具类型。它仍然不知道它是否有价值,将其视为{},它是一个空对象,不能分配给操作。

      【讨论】:

        猜你喜欢
        • 2018-06-22
        • 2021-09-11
        • 2018-10-24
        • 1970-01-01
        • 2021-12-03
        • 2022-06-12
        • 2022-01-18
        • 2019-05-12
        • 1970-01-01
        相关资源
        最近更新 更多