代码与说明

  • 作用:挂载时注入样式,卸载时移除;
import { useEffect } from 'react';
 
export const useComponentStyles = (
  styleId: string,
  isMinHeight: boolean = false,
  customStyle: string = ''
) => {
  useEffect(() => {
    if (!document.getElementById(styleId)) {
      const style = document.createElement('style');
      style.id = styleId;
      style.textContent = `
      ${isMinHeight ? 'div#root>div.ant-layout { height: 100vh; }' : ''}
      ${customStyle}
      `;
      document.head.appendChild(style);
    }
    return () => document.getElementById(styleId)?.remove();
  }, [styleId, isMinHeight, customStyle]);
};