![](/img/trans.png)
[英]Property 'navigation' does not exists on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>
[英]Property 'XYZ' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'
嘗試訪問 RecipeList.js 和 Recipe.js 的 .props 時出現語法錯誤。
這是 Recipe.js 的代碼示例:
import React, {Component} from 'react';
import "./Recipe.css";
class Recipe extends Component {
// props: any; uncommenting this will fix the bug
render() {
// don't have to use return and parentheses for arrow with JSX
const ingredients = this.props.ingredients.map((ing, ind) => (
<li key={ind}>{ing}</li>
));
const {title, img, instructions} = this.props
return (
<div className="recipe-card">
<div className="recipe-card-img">
<img src={img} alt={title}/>
</div>
<div className="recipe-card-content">
<h3 className="recipe-title">
{title}
</h3>
<h4>
Ingredients:
</h4>
<ul>
{ingredients}
</ul>
<h4>
Instructions:
</h4>
<p>
{instructions}
</p>
</div>
</div>
)
}
}
但是,該項目不會引發任何編譯時錯誤,並且該網站運行良好。
應用程序運行良好且沒有 chrome 控制台或終端錯誤的屏幕截圖
我認為這與我的代碼無關,而與 TypeScript 或某種帶有 Javascript 的預設配置有關,用於 VScode 無法識別每個組件的 .props 屬性,因為我在將React Tutorial Project構建到其中時遇到了類似的問題我的編輯器(為了確定起見,我什至從站點復制粘貼了最終的 index.js 代碼),盡管該應用程序運行良好,沒有編譯時錯誤。
解決這個問題的唯一方法是,如果我實際硬編碼並為每個類創建一個 props 屬性並將其設置為任何如下所示:
這是我更新的依賴項
"dependencies": {
"@types/react": "^16.4.13",
"prop-types": "^15.6.2",
"react": "^16.5.0",
"react-dom": "^16.5.0",
"react-scripts": "1.1.5",
"typescript": "^3.0.3"
}
您需要使用接口和 TypeScript 的 React.Component 通用實現來定義道具和狀態的外觀
import React, {Component} from 'react';
import "./Recipe.css";
interface IRecipeProps {
ingredients?: string[];
title?: string;
img?: string;
instructions?: string;
}
interface IRecipeState {
}
class Recipe extends Component<IRecipeProps, IRecipeState> {
render() {
const ingredients = this.props.ingredients.map((ing, ind) => (
<li key={ind}>{ing}</li>
));
const {title, img, instructions} = this.props
return (
<div className="recipe-card">
Your render code here
</div>
)
}
}
.tsx
以表明它是一個使用 TypeScript -> Recipe.tsx
的 React 文件IRecipeState
來定義組件狀態的結構( this.state.fooBar
)。 現在可以將其留空,因為您不使用狀態。RecipeList.js
)基於Klugjos 的回答。 您可以對 React 的功能組件 (FC) 執行相同操作,並使用 useState Hook 來管理狀態。
import React, {FC} from 'react';
import "./Recipe.css";
interface IRecipeProps {
ingredients?: string[];
title?: string;
img?: string;
instructions?: string;
}
interface IRecipeState {
}
const Recipe:FC<IRecipeProps> = (props) => {
const { ingredients, title, img, instructions} = props;
ingredients.map(( ingredient, index) => (
<li key={index}>
{ ingredient}
</li>
));
return (
<div className="recipe-card">
Your render code here
</div>
)
}
您也可以通過以下方式解決此問題
class Recipe extends React.Component<any, any>{
....
....
// The rest of your normal code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.