函数式组件与类组件

使用起来没什么不同,只是在创建的时候稍有区别
robot函数式组件:

import React from "react";
import styles from "./robot.module.css"

interface RobotProps {
  id: number;
  name: string;
  email: string;
}
// 定义Robot为函数组件,<RobotProps>泛型类型,可写为{props},propt用来传递数据,此处使用解构赋值直接展开数据{ id, name, email }
const Robot: React.FC<RobotProps> = ({ id, name, email }) => {
  return (
    <div className={styles.cardContainer}>
      <img alt="robot" src={`https://robohash.org/${id}`} />
      <h2>{name}</h2>
      <p>{email}</p>
    </div>
  );
};

export default Robot;

ShoppingCard类组件

import { render } from "@testing-library/react";
import React from "react";
import { isPropertySignature } from "typescript";
import styles from "./ShoppingCart.module.css"
interface Props { }
interface State {
    isOpen: boolean;
}
//  创建class类组件,继承React.Component类,传入参数Props, State
class ShoppingCart extends React.Component<Props, State>{
    constructor(props: Props) {
        super(props);
        this.state = {
            isOpen: false
        }
    }

    render() {
        return (
            <div className={styles.cartContainer}>
                <button className={styles.button} onClick={() => {
                    this.setState({ isOpen: !this.state.isOpen })
                }}>
                    购物车2(件)
                </button>
                <div className={styles.cartDropDown} style={{ display: this.state.isOpen ? "block" : "none" }}>
                    <ul>
                        <li>robot1</li>
                        <li>robot2</li>
                    </ul>
                </div>
            </div >
        )
    }

}

export default ShoppingCart
posted @ 2022-02-21 15:20  黑蛋的博客  阅读(74)  评论(0编辑  收藏  举报