React+TS前台项目实战-- 响应式头部导航+切换语言相关组件封装
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Dropdown, Icon } from 'semantic-ui-react';
interface LanguageOptionProps {
text: string;
value: string;
image: string;
}
const LanguageOptions: LanguageOptionProps[] = [
{ text: 'English', value: 'en', image: '../../images/en.png' },
{ text: '中文', value: 'zh', image: '../../images/cn.png' }
];
const TopNav: React.FC = () => {
const { t, i18n } = useTranslation();
const [language, setLanguage] = useState(i18n.language);
const handleLanguageChange = (_, data: any) => {
const { value } = data;
i18n.changeLanguage(value);
setLanguage(value);
};
return (
<div className="topnav">
<div className="topnav-wrapper">
<Link to="/" className="topnav-logo">
<img src="../../images/logo.png" alt="Logo" />
</Link>
<div className="topnav-menu">
<Link to="/" className="item">{t('Home')}</Link>
<Link to="/about" className="item">{t('About')}</Link>
<Link to="/contact" className="item">{t('Contact')}</Link>
<Dropdown
text={t('Language')}
icon={<Icon name="world" />}
className="language-dropdown"
options={LanguageOptions.map(option => ({
...option,
text: t(option.text),
image: { avatar: true, src: option.image }
}))}
onChange={handleLanguageChange}
value={language}
/>
</div>
</div>
</div>
);
};
export default TopNav;
这个代码实例使用了React Hooks和TypeScript来创建一个响应式的头部导航组件,其中包括一个下拉菜单来切换语言。它使用了react-i18next
库来处理国际化,并且展示了如何使用Dropdown
组件从semantic-ui-react
库来创建语言切换功能。
评论已关闭