react 与 项目结合
由下面的两幅图,我们可以知道。 定义一个函数式组件时,给props传参有两种方法。
1、const Person = (props: PersonProps) => { }
2、const ComponentA: React.FC<ComponentAProps> = ( props )=> { }
---------------------
import React, { useState } from 'react';
type ListItemType = {
id: number;
name: string;
description: string;
};
interface PersonProps {
name: string;
description: string;
}
const Person = (props: PersonProps) => {
const { name, description } = props;
return (
<div>
<p>我是: {name}</p>
<p>描述: {description}</p>
</div>
);
};
export default () => {
const [list, setList] = useState<ListItemType[]>([
{
id: 1,
name: '张三',
description: '身高185,体重150',
},
{
id: 2,
name: '李四',
description: '身高168,体重160',
},
]);
const handleSpliceItem = (index: number) => {
const newList = [...list];
if (index !== -1) {
newList.splice(index, 1);
} else {
newList.push({
id: +Math.random().toFixed(16).slice(2, 10),
name: 'name',
description: 'description',
});
}
setList(newList);
};
return (
<div>
{/* 正确示范 */}
{list.map((item) => (
<Person key={item.id} {...item} />
))}
{/* 错误示范 */}
{list.map((item, index) => (
<Person key={index} {...item} />
))}
<button style={{ marginRight: 10 }} onClick={() => handleSpliceItem(list.length - 1)}>
删除最后一项
</button>
<button onClick={() => handleSpliceItem(-1)}>添加一项</button>
</div>
);
};
import React from 'react';
interface ComponentAProps {
title: string;
description?: string;
visibleExtra?: boolean;
}
const ComponentA: React.FC<ComponentAProps> = (props) => (
<div>
<h3>{props.title}</h3>
<p>{props.description}</p>
{props.visibleExtra && <div>被你看到了额外内容</div>}
</div>
);
ComponentA.defaultProps = {
visibleExtra: false,
};
export default () => (
<div>
<ComponentA title="标题1" description="我是描述1" />
<ComponentA title="标题2" description="我是描述2" visibleExtra />
</div>
);