高阶函数与高阶组件到底是什么

119 阅读2分钟

高阶函数

如果一个函数接受的参数为函数,或者返回值是一个新函数,则该函数就是高阶函数

  • 例如

    setTimeout(()=>{},1000);
    

高阶组件

如果一个组件的参数是组件,返回值是一个新组件,则该组件就是高阶组件

  • 例如
export const HOCView = (rootView) => {
    const tView = (props) => {
        return (<View>  </View>);
    };
    return tView;
}

高阶组件应用场景

使用 HOC 高阶组件解决横切关注点问题,使得组件功能更加单一,组件逻辑服务组件ui,从而降低耜合性,增强组件的复用性

Hack 渲染函数:页面右下角添加按钮

  • 文件命名:通过以小写 with 开头=
  • 高阶组件的定义
    import {Image, StyleSheet, TouchableOpacity} from 'react-native';
    import image from '../assets/images/image.png';
    
    export default OrginView => {
      const HOCView = props => {
        return (
          <>
            {/* 首先要将传过来的参数回传回去,不可修改 */}
            <OrginView {...props} />
            {/* 以下是自定义的控件 */}
            <TouchableOpacity
              style={styles.button}
              onPress={() => {
                console.log('prsss on++');
              }}>
              <Image style={styles.addImage} source={image}></Image>
            </TouchableOpacity>
          </>
        );
      };
    
      return HOCView;
    };
    
    const styles = StyleSheet.create({
      button: {
        position: 'absolute',
        bottom: 64,
        right: 20,
      },
      addImage: {
        width: 54,
        height: 54,
        resizeMode: 'contain',
      },
    });
    
  • 高阶组件的使用
    import withFloatButton from '../hoc/withFloatButton';
    
    // 使用 withFloatButton 将 之前的组件包裹起来
    export default withFloatButton(
      (HeaderView = () => {
        // context 读取
        const theme = useContext(ThemeContext);
        // context 使用
        const styles = theme === 'dark' ? darkStyles : lightStyles;
        return (
          <View style={styles.content}>
            <Image style={styles.img} source={image}></Image>
            <Text style={styles.txt}>标题</Text>
          </View>
        );
      }),
    );
    

Hack 生命周期:首页上报设备信息

  • 定义:通过在组件的 useEffect 方法,执行对应的逻辑处理
import {useEffect} from 'react';

export default OrginView => {
  const HOCView = props => {
    useEffect(() => {
      uploadInfo();
      console.log('+++++');
    }, []);
    const uploadInfo = () => {
      const info = {
        name: 'xxx',
        mac: '12345',
      };
      // 执行网络请求
    };
    return (
      <>
        {/* 首先要将传过来的参数回传回去,不可修改 */}
        <OrginView {...props} />
      </>
    );
  };

  return HOCView;
};
  • 使用
import whitUpload from '../hoc/whitUpload';
// 使用 withFloatButton 将 之前的组件包裹起来
export default whitUpload(
  (HeaderView = () => {
    // context 读取
    const theme = useContext(ThemeContext);
    // context 使用
    const styles = theme === 'dark' ? darkStyles : lightStyles;
    return (
      <View style={styles.content}>
        <Image style={styles.img} source={image}></Image>
        <Text style={styles.txt}>标题</Text>
      </View>
    );
  }),
);

总结

综上所述,HOC 高阶组件在真实项目开发中是非常重要的解糯技巧,它解决的是横切点关注问题,把不同的职责和能力独立成高阶组件,增强了复用性,降低了轉合度。合理使用高阶组件可以使我们的代码更安全稳定,更好维护。