我在尝试访问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>
)
}
}
然而,该项目并没有抛出编译时错误,并且网站运行得非常好。
我认为这与我的代码关系不大,更多地与TypeScript或某种预设配置有关,因为VScode在识别每个组件的.props属性时遇到了麻烦,当我将React教程项目构建到我的编辑器中时(我甚至复制粘贴了网站上的最终index.js代码以确保正确),我遇到了类似的问题,尽管应用程序没有编译时错误,也能正常工作。
唯一解决这个问题的方法是如果我硬编码并为每个class创建一个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"
}