gdf*_*dfg 9 internationalization node.js i18next reactjs next.js
我正在将 NextJS 与 next-i18next 一起使用。这是我的主页:
import {withTranslation} from '../config/next-i18next';
const Home = function Home() {
return (<div>test</div>)
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);
Run Code Online (Sandbox Code Playgroud)
我想要的是在组件/页面中获取当前语言,我该怎么做?
fel*_*osh 13
withTranslation注入i18n对象。
import {withTranslation} from '../config/next-i18next';
const Home = function Home({ i18n }) {
return (<div>{i18n.language}</div>)
// ----------------^
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);
Run Code Online (Sandbox Code Playgroud)
或者使用钩子,
import {useTranslation} from '../config/next-i18next';
const Home = function Home() {
const { i18n } = useTranslation('home');
return (<div>{i18n.language}</div>)
// ----------------^
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default Home;
Run Code Online (Sandbox Code Playgroud)
小智 13
对于 Next.js,您还可以使用useRouter挂钩。
import {withTranslation} from '../config/next-i18next';
import { useRouter } from 'next/router'
const Home = function Home() {
const router = useRouter()
const currentLang = router.locale // => locale string eg. "en"
return (<div>test</div>)
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10780 次 |
| 最近记录: |