tsx
复制代码
import type { IUserInfo } from '@/types';
import storage from '@/utils/storage';
import {
LogoutOutlined,
MoonOutlined,
SunOutlined,
UserOutlined
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import {
Avatar,
Dropdown,
Switch,
message,
theme
} from 'antd';
import React, { useState } from 'react';
import { useAntdConfigSetter } from '@umijs/max'; // 需要打开配置才不会报错 antd: { configProvider: {} },
const { darkAlgorithm, defaultAlgorithm } = theme;
const RightRender = () => {
const { initialState, setInitialState } = useModel('@@initialState');
// 从 initialState 获取用户信息
const userInfo = initialState?.person as IUserInfo;
const setAntdConfig = useAntdConfigSetter();
console.log('setAntdConfig', setAntdConfig);
const [dark, setDark] = useState(false);
// 重点处理逻辑
const handleThemeChange = (checked: boolean) => {
console.log('checked', checked);
setDark(checked);
setAntdConfig({
theme: {
algorithm: [
checked ? darkAlgorithm : defaultAlgorithm
]
}
});
};
// 退出登录处理函数
const handleLogout = async () => {
try {
storage.clearAll();
// 更新初始状态
setInitialState(undefined);
history.push('/login');
message.success('退出登录成功');
} catch (error) {
message.error('退出登录失败');
}
};
// 下拉菜单项
const menuItems = [
{
key: 'logout',
icon: <LogoutOutlined />,
label: '退出登录',
onClick: handleLogout
}
];
return (
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
{/* 暗黑模式切换 */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
{dark ? <MoonOutlined /> : <SunOutlined />}
<Switch
checked={dark}
onChange={handleThemeChange}
size="small"
/>
</div>
{/* 用户头像和下拉菜单 */}
<Dropdown
menu={{ items: menuItems }}
placement="bottomRight"
trigger={['hover']}
>
<div
style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}
>
{userInfo.headImg ? (
<Avatar
src={
<img draggable={false} src={userInfo.headImg} alt="avatar" />
}
/>
) : (
<Avatar
style={{ backgroundColor: 'skyblue' }}
icon={<UserOutlined />}
/>
)}
<span style={{ marginLeft: '8px', fontSize: '14px' }}>
{userInfo?.nickName || userInfo?.name || '未知用户'}
</span>
</div>
</Dropdown>
</div>
);
};
export default RightRender;