HOC的运用

1. 防抖高阶组件 (Debounce HOC)


import React, { useState, useEffect } from 'react';
const debounce = (func, delay) => {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
};
const withDebounce = (Component, delay) => {
  return function(props) {
    const [inputValue, setInputValue] = useState('');
    const handleChange = (e) => {
      setInputValue(e.target.value);
    };
    
    useEffect(() => {
      const handleDebounce = debounce(props.onChange, delay);
      handleDebounce(inputValue);
    }, [inputValue]);
    return <Component {...props} inputValue={inputValue} onChange={handleChange} />;
  };
};
export default withDebounce;

使用示例:


import React from 'react';
import withDebounce from './withDebounce';
const SearchInput = (props) => {
  return <input type="text" value={props.inputValue} onChange={props.onChange} />;
};
const DebouncedSearchInput = withDebounce(SearchInput, 300);
export default DebouncedSearchInput;

2. 权限控制高阶组件 (Authorization HOC)


import React from 'react';
const withAuthorization = (Component, requiredRole) => {
  return function(props) {
    const userRole = getLoggedInUserRole();
    if (userRole !== requiredRole) {
      return <div>You do not have the required permissions to view this page.</div>;
    }
    return <Component {...props} />;
  };
};
export default withAuthorization;

使用示例:


import React from 'react';
import withAuthorization from './withAuthorization';
const AdminPanel = () => {
  return <div>This is the admin panel.</div>;
};
const AuthorizedAdminPanel = withAuthorization(AdminPanel, 'admin');
export default AuthorizedAdminPanel;

3. 异步加载高阶组件 (Async Loading HOC)


import React, { useState, useEffect } from 'react';
const withAsyncLoading = (Component) => {
  return function(props) {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    useEffect(() => {
      fetchData().then((data) => {
        setData(data);
        setIsLoading(false);
      });
    }, []);
    if (isLoading) {
      return <div>Loading...</div>;
    }
    return <Component {...props} data={data} />;
  };
};
export default withAsyncLoading;

使用示例:


import React from 'react';
import withAsyncLoading from './withAsyncLoading';
const DataDisplay = (props) => {
  return <div>{props.data}</div>;
};
const AsyncDataDisplay = withAsyncLoading(DataDisplay);
export default AsyncDataDisplay;

4. 状态管理高阶组件 (State Management HOC)


import React, { useState } from 'react';
const withState = (Component) => {
  return function(props) {
    const [count, setCount] = useState(0);
    const incrementCount = () => {
      setCount(count + 1);
    };
    const decrementCount = () => {
      setCount(count - 1);
    };
    return (
      <Component
        {...props}
        count={count}
        incrementCount={incrementCount}
        decrementCount={decrementCount}
      />
    );
  }
}
export default withState;

使用示例:


import React from 'react';
import withState from './withState';
const Counter = (props) => {
  return (
    <div>
      <button onClick={props.incrementCount}>+</button>
      <span>{props.count}</span>
      <button onClick={props.decrementCount}>-</button>
    </div>
  );
};
const CounterWithState = withState(Counter);
export default CounterWithState;

5. 日志记录高阶组件 (Logging HOC)


import React, { useEffect } from 'react';
const withLogging = (Component) => {
  return function(props) {
    useEffect(() => {
      console.log('Component mounted');
      return () => {
        console.log('Component unmounted');
      };
    }, []);
    return <Component {...props} />;
  };
};
export default withLogging;

使用示例:


import React from 'react';
import withLogging from './withLogging';
const MyComponent = () => {
  return <div>Hello World!</div>;
};
const LoggedComponent = withLogging(MyComponent);
export default LoggedComponent;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天吃饭的羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值