代码之家  ›  专栏  ›  技术社区  ›  HelloWorld1

带参数的函数不会显示在VS代码中

  •  0
  • HelloWorld1  · 技术社区  · 4 年前

    目标:
    允许将函数Test2与参数值“Test2”一起使用,然后在Visual Studio代码中显示,且不会出现任何错误。

    问题:
    当我应用代码“<Test2 thename={'Test2'}/>”和“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代码中工作,我错过了什么?

    信息:
    *反应中的新手
    *它适用于stackblitz,但不适用于VS代码( 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>
      );
    }
    
    1 回复  |  直到 4 年前
        1
  •  0
  •   Serhiy Mamedov    4 年前

    在Typescript中,如果不为函数指定参数类型,它将自动被指定为any。 但是,如果不更改typescript的默认配置,则此类型asignent将引发错误。这不仅限于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:组件不应在其他组件内定义。每个组件都应该在顶层定义(就像你的应用程序组件一样)。