尝试访问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>
)
}
}然而,该项目没有抛出编译时错误,网站运行得很好。
Screenshot of app working fine with no chrome console or terminal errors
我认为这与我的代码关系不大,更多的是与TypeScript或VScode的某种预设配置有关,因为当我在编辑器中构建React Tutorial Project时,我遇到了类似的问题(我甚至复制粘贴了网站上的最终index.js代码,没有编译时错误),因此无法识别每个组件的.props属性。
Screenshot of the same .prop errors after following React Tutorial
解决这个问题的唯一方法是,如果我真的硬编码,为每个类创建一个props属性,并将其设置为任何类似的属性:
Screenshot of only solution to the syntax error
下面是我更新后的依赖项
"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"
}发布于 2018-09-10 09:36:45
您需要使用React.Component的interface和TypeScript的通用实现来定义您的属性和状态
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
IRecipeState ->使用
this.state.fooBar)的结构。暂时将其保留为空是可以的,因为您不使用状态。
RecipeList.js)的其他组件执行相同的操作
发布于 2020-05-30 08:46:43
基于答案。您可以对React的功能组件( functional component,FC)执行相同的操作,并使用useState挂钩来管理状态。
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>
)
}发布于 2021-07-02 04:55:26
您也可以使用以下命令来解决此问题
class Recipe extends React.Component<any, any>{
....
....
// The rest of your normal code
}https://stackoverflow.com/questions/52249390
复制相似问题