目標:
允許使用帶有引數值“Test 2”的函式 Test2,然后在 Visual Studio Code 中顯示而不會出現任何錯誤。
問題:
當我應用代碼“<Test2 thename={'Test 2'} />”和“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(不會顯示帶引數的函式)
* 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="帶有引數的函式不會顯示在 VS Code 中" />
<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>
);
}
uj5u.com熱心網友回復:
在 Typescript 中,如果您沒有為函式分配引數型別,它將自動分配為 any。但是,如果您不更改打字稿的默認配置,則此型別分配會引發錯誤。這不僅限于 jsx,這只是 TS 的作業方式。
有幾種方法可以克服這個問題。
- 為您的引數定義介面并設定為型別:
interface Props {
thename: string;
}
function Test2(props: Props) {
return <h1>{props.thename} works!</h1>;
}
這是最好的選擇。
- 明確分配任何型別:
function Test2(props: any) {
return <h1>{props.thename} works!</h1>;
}
- 更改
tsconfig.json并允許隱式任何。
PS:組件不應定義在另一個組件中。每個組件都應該在頂層定義(就像你的 App 組件一樣)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/400843.html
