如何在next.js中将阿拉伯文转换为英语

0vvn1miw  于 2022-12-18  发布在  其他
关注(0)|答案(2)|浏览(203)
import Image from 'next/image'
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
function Language() {
    const { pathname, locale, push, asPath } = useRouter();
    const lng = locale == "en" ? "ar" : "en";
    const dir = locale === "en" ? "ltr" : "rtl";
    useEffect(() => {
        document.dir = dir;
        if (dir === "ltr") {
        document.body.classList.add("ltr");
        document.body.classList.remove("rtl");
        } else {
        document.body.classList.add("rtl");
        document.body.classList.remove("ltr");
        }
    }, [dir]);
    const toggleLanguage = () => {
        document.dir = dir;
        if (lng === "en") {
        document.body.classList.add("ltr");
        document.body.classList.remove("rtl");
        } else {
        document.body.classList.add("rtl");
        document.body.classList.remove("ltr");
        }
        push(pathname, asPath, { locale: lng });
    };
    return (
        <div className="language">
            <div className="lan__country active us flex items-center cursor-pointer" onClick={toggleLanguage} >
                <div className="flag flag1">
                    <div className="dark-none">
                        <Image src="/en.svg" width="20" height="20"alt="us flag" className='dark-none' />
                    </div>
                    <div className="d-none dark-show">
                        <Image src="/lang_white.svg" width="20" height="20"alt="us flag" className='d-none dark-show' />
                    </div>
                </div>
                <div className="flag flag2">
                    <div className="dark-none">
                        <Image src="/en.svg" width="20" height="20"alt="us flag" className='dark-none' />
                    </div>
                    <div className="d-none dark-show">
                        <Image src="/lang_white.svg" width="20" height="20"alt="us flag" className='d-none dark-show' />
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Language

如何在next.js中将阿拉伯文转换成英语?我已经成功地通过点击按钮改变了方向,但是我也想改变文本。我只做前端。

tzdcorbm

tzdcorbm1#

有多种方法可以做到这一点。如果你有来自数据库的动态文本,你可以使用i18(https://www.i18next.com/)进行翻译。
如果您只是想将硬编码数据更改为另一种语言,您应该将所有静态数据写入json文件中的一个对象中,并通过键(en:...,ar:...)
示例:

  • 〉数据. json
{
  en:{
    "title":"This is En Language",
    "name":"My Name Is F"
  },
  ar:{
    "title":"سلام علیکم",
    "name":"تعلم"
  }
}
  • 〉索引. js
import {data} from "./folder/data.json;
import { useRouter } from "next/router";

const Home=()=>{
  const {locale}=useRouter()
  const myData=data[locale]

  return (
    <div>
       <h1>title = {myData.title}</h1> 
       <p>Name = {myData.name} </p>
    </div>)
}

相关问题