import React, { useCallback, useState } from 'react' import { Box, Icon, Radio, Select } from '@alifd/next' const THEME_LIST = [ { label: '主题:Orange 阿里橙', code: 'theme-1', value: '//unpkg.com/@alifd/theme-1/variables.css' }, { label: '主题:Blue 极客蓝', code: 'theme-2', value: '//unpkg.com/@alifd/theme-2/variables.css' }, { label: '主题:Purple 菖蒲紫', code: 'theme-3', value: '//unpkg.com/@alifd/theme-3/variables.css' }, { label: '主题:Green 松石绿', code: 'theme-4', value: '//unpkg.com/@alifd/theme-4/variables.css' } ] export default function ThemeSelect () { const [loading, setLoading] = useState(false) const changeTheme = useCallback((href) => { // 方法 1,工具方法 loadRemoteStyle 只适合加载远程 CSS 文件,不适合替换场景。因为会自动插入新节点,并永久缓存,导致和移除操作冲突。 // setLoading(true) // loadRemoteStyle(item.href).then((element: any) => { // // 移除其他主题文件 // document.head.querySelectorAll('[data-group="alifd-theme"]') // .forEach(item => { // if (item !== element) document.head.removeChild(item) // }) // element.setAttribute('data-group', 'alifd-theme') // setLoading(false) // }) // 方法 2,√ 可以保证加载顺序,X 无法获取加载状态 // const link = document.getElementById('alifd_theme') // if (link) link.href = item.href // 方法 3,X 无法保证加载顺序,√ 可以获取加载状态 setLoading(true) const curr = document.getElementById('alifd_theme') const next = document.createElement('link') next.type = 'text/css' next.href = href next.rel = 'stylesheet' next.id = 'alifd_theme' next.onload = () => { if (!curr?.parentNode) return curr.parentNode.removeChild(curr) // 移除当前主题文件 setLoading(false) } if (curr?.parentNode) curr.parentNode.insertBefore(next, curr) // 不使用 document.head,是为了自动适配插入位置。 }, []) return <>

Theme Switcher

{ changeTheme(value) }} />