【问题标题】:how to set onChange handler to change the language in react i18next如何设置 onChange 处理程序以更改反应 i18next 中的语言
【发布时间】:2022-02-10 17:55:38
【问题描述】:

-允许用户更改语言的选择表单不适用于 onclick 我如何使用 onChange 处理程序

  • 我正在使用 react i18next。

*请记住,没有收到任何错误或警告。 这是我的代码

import i18n from 'i18next';

export default function Footer() {
const languages = [
    {
      code: "fr",
      name: "francais",
      countryCode:"fr"
    },
    {
      code: "en",
      name: "english",
      countryCode:"gb"
    },
    {
      code: "ar",
      name: "العربية",
      countryCode:"sa"
    }
  ]


return <Form.Select aria-label="Default select example" >
{languages.map(({code,name, countryCode})=>{
  return(
    <option key={countryCode} onClick={()=> i18n.changeLanguage(code)}>{name}</option>
  )
})}
</Form.Select>
}

【问题讨论】:

  • 你能提供一个可重现的例子吗,可能是在codesandbox或类似的地方?

标签: reactjs i18next


【解决方案1】:

需要在 Form.Select 组件上设置用于更改语言的 onChange 处理程序,如下所示:https://codesandbox.io/s/react-code-works-on-mozilla-but-but-dont-on-chrome-forked-1lkvw?file=/src/Footer.js:579-657

import { useTranslation } from "react-i18next";
import { Container, Form } from "react-bootstrap";

export default function Footer() {
  const { i18n } = useTranslation();

  const languages = [
    {
      code: "fr",
      name: "francais",
      countryCode: "fr"
    },
    {
      code: "en",
      name: "english",
      countryCode: "gb"
    },
    {
      code: "ar",
      name: "العربية",
      countryCode: "sa"
    }
  ];

  return (
    <div className="section footer">
      <Container>
        <Form.Select
          defaultValue={i18n.resolvedLanguage}
          onChange={e => {
            i18n.changeLanguage(e.target.value);
          }}
        >
          {languages.map(({ code, name, countryCode }) => {
            return (
              <option
                key={countryCode}
                value={code}
              >
                {name}
              </option>
            );
          })}
        </Form.Select>
      </Container>
    </div>
  );
}

【讨论】:

  • 非常感谢它有效。但是我仍然不明白为什么当我在选项标签上使用点击事件时它不起作用??
  • 因为option标签没有onClick
猜你喜欢
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 2021-04-23
  • 2015-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多