react 与 项目结合

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>
);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值