【问题标题】:Function with argument won't display in VS Code带参数的函数不会在 VS Code 中显示
【发布时间】:2022-01-01 08:58:56
【问题描述】:

目标:
允许使用带有参数值“Test 2”的函数 Test2,然后在 Visual Studio Code 中显示而不会出现任何错误。

问题:
当我应用代码“”和“function Test2”时,它显示错误提示

Compiled with problems:X

ERROR in src/App.tsx:11:18

TS7006: Parameter 'props' implicitly has an 'any' type.
     9 |   }
    10 |
  > 11 |   function Test2(props) {
       |                  ^^^^^
    12 |     return <h1>{props.thename} works!</h1>;
    13 |   }
    14 |

我缺少在 VS 代码中工作的顺序是什么?

信息:
*ReactTS 新手
*它适用于 stackblitz 但不适用于 VS Code (Function with argument won't display)
*https://stackblitz.com/edit/react-ts-atrrsi?file=index.tsx

谢谢!

import React from 'react';
import logo from './logo.svg';
import './App.css';

export default function App() {

  function Test1() {
    return <h1>Test 1 works!</h1>;
  }

  function Test2(props) {
    return <h1>{props.thename} works!</h1>;
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>

        <Test1 />
        <Test2 thename={'Test 2'} />        
      </header>
    </div>
  );
}

【问题讨论】:

  • 您是否已经搜索过错误消息?它让您知道您的变量是无类型的,并且您可能有一个不允许隐式“任何”类型的规则。

标签: visual-studio-code react-tsx


【解决方案1】:

在 Typescript 中,如果您没有为函数分配参数类型,它将自动分配为 any。 但是,如果您不更改 typescript 的默认配置,则此类型分配将引发错误。这不仅限于 jsx,它就是 TS 的工作方式。

有几种方法可以解决这个问题。

  1. 为您的参数定义接口并设置为类型:
interface Props {
    thename: string;
}

function Test2(props: Props) {
    return <h1>{props.thename} works!</h1>;
}

这是最好的选择。

  1. 显式分配任何类型:
function Test2(props: any) {
    return <h1>{props.thename} works!</h1>;
}
  1. 更改 tsconfig.json 并允许隐式任何。

PS:组件不应定义在另一个组件中。每个组件都应该在顶层定义(就像您的 App 组件一样)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2021-10-24
    • 2022-09-27
    • 2022-01-18
    • 1970-01-01
    • 2018-02-05
    相关资源
    最近更新 更多