react的组件创建类型

一、类组件(有状态组件)

有props.控制状态state,可以试用生命周期函数

1. 类名称必须以大写字母开头 

2. 类组件必须继承React.Component父类,从而可以使用父类中提供的方法或属性 

3. 类组件必须提供render()方法

4. render()方法必须要有返回值

import React form 'react';

class CreatDom extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      loading: true;
    }
  }
  componentDidUpdate(preProps) {
    this.setState({loading: false})
  }
  onClick(e) {
    console.log(e)
  }
render () { return <div onClick={this.onClick}> hello word!! {this.state.loading}</div> } } export default CreatDom;

  

二、纯函数组件(无状态组件)

函数式定义组件没有state和生命周期函数且不能访问this,而类定义中这些都可以有。组件只需要做静态页面的展示而没有复杂的用户交互以及状态更新,我们推荐使用函数组件。

1. 函数组件名称必须以大写字母开头;

2. 函数组件必须要有返回值

export interface BreadcrumbsProps {
  items: {
    href: string;
    text: string;
  }[];
}
function Breadcrumbs(props: BreadcrumbsProps) {
  const { pathname } = useLocation();
  return (
    <BreadcrumbList>
      {props.items.map(({ href, text }) =>
        href === pathname ? (
          <span
            className={`t--breadcrumb-item ${
              href === pathname ? `active` : ``
            }`}
            key={href}
          >
            {text}
          </span>
        ) : (
          <Link
            className={`t--breadcrumb-item ${
              href === pathname ? `active` : ``
            }`}
            key={href}
            to={href}
          >
            {text}
          </Link>
        ),
      )}
    </BreadcrumbList>
  );
}

export default Breadcrumbs;

  

 

***组件不要变成复杂的容器,最好只是数据流的管道。开发者根据需要,组合管道。组件的最佳写法应该式函数,不是类。

无论使用哪种方式创建组件,组件名称的首字母都必须大写,因为我们写的是JSX;

posted @ 2023-03-23 14:14  这是啥!啥!啥  阅读(34)  评论(0编辑  收藏  举报