【问题标题】:React TypeScript Error : TS2322 - Type '' is not assignable to type 'IntrinsicAttributes & String'React TypeScript 错误:TS2322 - 类型“”不可分配给类型“IntrinsicAttributes & String”
【发布时间】:2020-11-09 07:12:32
【问题描述】:

我有一个新的 .tsx 文件,我希望将标题传递给我的组件。但是,属性“title”使用下面的简单代码返回以下错误。

键入'{标题:字符串; }' 不可分配给类型 'IntrinsicAttributes & String'。 “IntrinsicAttributes & String”类型上不存在属性“title”。 TS2322

import React from 'react';
import { render } from 'react-dom';
import { Nav } from "./sections";

render(
  <Nav title="Suite" />,
  document.getElementById('root')
);

我的 Nav 组件的代码如下:

import React from "react";

export const Nav = (title: String) => {
  return <ul><li>{title}</li></ul>;
};

我仍在进行故障排除,我想知道修复是否与我的 TSConfig 有关。欢迎任何建议。

如果有帮助,这里是我的 tsconfig.json 的副本

    {
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

【问题讨论】:

  • 请将Nav 组件(或至少部分)添加到问题中,因为它的道具类型可能与问题相关。
  • 完成。我已经添加了导航组件的基本代码。
  • React 函数组件是一个接受单个 props 对象参数的函数,但您将其键入为字符串。见how to type function components' props with TypeScript.

标签: javascript reactjs typescript jsx typescript-eslint


【解决方案1】:

如果您的 Nav 组件是功能组件,那么您可以将类型传递给它,如下所示:

const Nav: React.FC<React.HTMLProps<Element>> = (props => {---your component code---})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2019-03-19
    • 2017-09-25
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    相关资源
    最近更新 更多