reactHook使用高阶组件

Hook 使用高阶组件

高阶公共组件

// 以下示例中是将重复的接口直接封装成高阶组件,实现复用

import React, { useState, useEffect } from 'react'
import { getCompanyList } from '@/services/home'
const ComponentNameInterface = (OriginalComponent: any, propsHoc: () => void) => {
  const Component: React.FC = (props: any) => {
    console.log(props)
    const [companyName, setCompanyName] = useState([])
    const companyListFun = (data: string | number | undefined | null) => {
      getCompanyList({word: data}).then(res => {
        console.log(res)
        if(res.code === '200') {
          setCompanyName(res.data || [])
        }
      }).catch(err => {
        console.error(err)
        setCompanyName([])
      })
    }
    useEffect(() => {
      companyListFun(null)
    }, [props])
    return 
      
我是高阶组件的内容 {propsHoc()}
} return Component } export default ComponentNameInterface

使用高阶组件的方法:

import React from 'react'
import { Input } from 'antd'
import HoCComponent from '@/components/Hoc/ComponentNameInterface'
type HocProps = {
  getCompanyName: (data: string | number | undefined | null) => void;
}
const Hoc: React.FC = (props) => {
  console.log(props)
  const inputChange = (e: any) => {
    props.getCompanyName(e.target.value)
  }
  return <>
    我是要使用高阶组件
    {props.children}
    
  
}
export default HoCComponent(
  Hoc,
  () => {
    return 
hahahahahhhahhahah
} )

注:我这里做的笔记只是基础,实际上在项目针对使用高阶组件这个方法使用封装上,大大减少了我代码的复用性,而且代码非常整洁,规整。

当不同的接口放在不同的高阶函数中如何调用那? 链式调用就可以了

// 企业名称 组件1
import ComponentNameInterface from '@/components/Hoc/ComponentNameInterface';
// 引入 行业类型  组件2
import IndustryListInterface from '@/components/Hoc/IndustryListInterface'

IndustryListInterface(ComponentNameInterface(EmissionsListing, undefined, false), undefined)

注:官网上有提供一些connect等方式链接,但是因为我目前的是一个中小型的项目,如果只是为了把多个组件融合成一个组件却只使用一个connect方法,那就是大才小用了。所以在这里我使用了链式的方法。

高阶组件 – React (docschina.org)

如何在一个组件内引用高阶组件,然后在组件内使用高阶组件封装标签小块儿功能
我们使用高阶组件在页面中使用,通常使用共同的封装方法和一些公共的数据,但是我想要将不同的antdPro图表中的所有不同标签放在一个组件中,通过不同的传参然后显示不同的图表,这种方法我使用回调函数拿到了内容后,在回调的函数内,我不能使用useState的方法去set拿值,所有我通过在回调内直接接受参数,然后return出去标签,这个是通过react中的函数的一个方法去显示标签的。

/**
 *  这是所有使用antdCharts的一个封装组件,通过在传type类型去显示对应的图表
 *  如有新增的内容的尽量不要再HocEcharts中修改,而是在单个使用这个组件的标签
 *  上传对应的属性,而所传的对应属性和使用AntdCharts 是一样的。
 *
 *  简单使用示例:
 *  
 */
import React, { useState, useEffect } from 'react';
import { colorBg } from '@/config';
import type { PieProps } from './PieComponent';
import { ConfigGlobla } from './ConfigGlobla';
import { Pie, Line, Bar, Column, Area, Heatmap } from '@ant-design/charts';
import ChartsEmpty from '../Empty/ChartsEmpty';
const HocEcharts = (OriginalComponent: any) => {
  const Component: React.FC = (props: any) => {
    const [configList, setConfigList] = useState({ ...ConfigGlobla });
    useEffect(() => {
      setConfigList({ ...ConfigGlobla });
    }, []);
    
    // 在这里return出去一个个独立的标签功能
    const setTypeChange = (list: any) => {
      const { type, data, height, color, dealWith, isColor } = list;
      let paramList: any[] = [];
      if (type === 'Heatmap') {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        data &&
          data.forEach((item: any) => {
            const monthData = item.troubleTypeList.map((cItem: any) => ({
              ...cItem,
              month: item.month,
            }));
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            paramList = [...paramList, ...monthData];
          });
      } else if (type === 'Bar' && dealWith) {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        data &&
          data.forEach((item: any) => {
            const tmpList = item.troubleList.map((cItem: any) => ({
              ...cItem,
              cateName: item.cateName,
            }));
            paramList = [...paramList, ...tmpList];
          });
      }
      const paramObj = {
        ...configList,
        ...list,
        data: JSON.stringify(paramList) !== '[]' ? paramList : data,
        line: undefined,
        smooth: true,
        meta: { month: { type: 'cat' }, count: { alias: '值' } },
        legend: {
          layout: 'horizontal',
          position: 'bottom',
          padding: [30, 0, 0, 0],
          flipPage: false,
        },
        color:
          color ||
          (isColor &&
            (({ level }: any) => {
              if (level) {
                return colorBg[level];
              }
              return null;
            })),
      };
      const Params = {
        Area: ,
        LineSolid: ,
        Column: ,
        Pie: ,
        Bar: ,
        Heatmap: ,
      };
      return data.length > 0 ? Params[type] : ;
    };
    const getConfig = (data: any) => {
      return <>{setTypeChange(data)};
    };
    return ;
  };
  return Component;
};
export default HocEcharts;

这就是我封装组件的一个示例。 使用方式

// 引入
import HocEcharts from '@/components/EchartsComponents/HocEcharts';
组件内任意地方使用:

// 导出

export default HocEcharts(ChartsComponent);

有什么疑问或者笔记哪里有问题还请指出,大家可一起交流。感谢观看!

你可能感兴趣的:(React,react.js,javascript,es6)