我是 React 的新手。我有一些用 React 编写的代码片段,其中 prop 从父组件传递到子组件,我正在使用功能组件( const 箭头函数)。但是,有一个我不明白的 any keyword 的用法。
我的父组件:
const text = {
title: "We Made Always Provide Quality Items",
para1:
"Excepteur sint occaecat cupidatat non proident sunt iculpa qui officia deserunt mollit anim est. . ",
para2:
"Dicta sunt explicabo. nemo enuam eius .",
thumbnails: [{ src: "" }],
};
const AboutPage = () => {
return (
<div className="about-page">
<PageHeader
title={titleContent.title}
subtitle={titleContent.subtitle}
btnText="">
<StatsCards stats={stats} />
</PageHeader>
<WhyUs />
<SideBySide {...text} />
<Chefs chefs={chefs} />
<ContentE />
</div>
);
};
我的子组件(SideBySide):
const SideBySide = (props: any) => {
return (
<div className="side-by-side">
<div className="container">
<div className="left-side">
<div className="title">
<div className="main-title">{props.title}</div>
</div>
<div className="description">
<p>{props.para1}</p>
<p>{props.para2}</p>
</div>
{/* Link to about us */}
<Link to="/menu">
<ExploreButton active="link-active">More About Us</ExploreButton>
</Link>
</div>
<div className="right-side">
<div className="image">
{props.thumbnails.map((thumbnail: any, index: number) => {
return (
<img
src={thumbnail.src}
alt=""
key={index}
className={`img-${index}`}
/>
);
})}
</div>
</div>
</div>
</div>
);
};
在 sidebyside 组件中,使用了 props: any
,我不明白它实际上在做什么。
直到现在,我只是使用 props 关键字在组件中传递 props 并以 props.name 的形式渲染作为示例。
最佳答案
这是一个 typescript 类型,支持从其他组件接收的所有类型的字段
const SideBySide = (props: any) => {
但是如果你只在 react 中,你可以删除类型并像这样使用
const SideBySide = (props) => {
typescript 示例
interface PersonProps {
name: string;
src: string;
age: number
}
let person: PersonProps = {
name: 'John',
src: 'http://...',
age: 30
}
但是如果你不想定义字段级类型你可以使用any
like
let person: any = {
name: 'John',
src: 'http://...',
age: 30
}
为了更好地理解,请参阅 TypeScript official documentation
关于javascript - React 功能组件中的 Prop 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68428639/