0

我使用 react-i18next 进行国际化,但我找不到任何内置方法来翻译 React 表单上的验证约束。表单消息的语言取决于浏览器的语言,如果用户选择在我的网站上使用不同的语言,则不会改变。

示例屏幕截图- 查看页面是英文的,但约束消息仍然是荷兰语。

有没有办法让验证约束的消息依赖于语言 cookie 进行翻译?或者也许可以用 react-i18next 翻译它们?

i18n.js:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from 'i18next-browser-languagedetector';

const resources = {
  en: {
    translation: {
      "Name": "Name",
      "Count": "Count",
      "New object": "New object",
      ...,
    }
  },
  nl: {
    translation: {
      "Name": "Naam",
      "Count": "Telling",
      "New object": "Nieuw object",
      ...,
    }
  }
};

i18n
  .use(LanguageDetector)
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    fallbackLng: "en",
    debug: false,

    keySeparator: false,

    interpolation: {
      escapeValue: false
    },
    detection: {
      // order and from where user language should be detected
      order: ['cookie', 'querystring', 'localStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],

      // keys or params to lookup language from
      lookupQuerystring: 'lng',
      lookupCookie: 'language',
      lookupLocalStorage: 'i18nextLng',
      lookupFromPathIndex: 0,
      lookupFromSubdomainIndex: 0,

      // cache user language on
      caches: ['localStorage', 'cookie'],
      excludeCacheFor: ['cimode'], // languages to not persist (cookie, localStorage)

      // optional expire and domain for set cookie
      cookieMinutes: 10,
      cookieDomain: 'myDomain',

      // optional htmlTag with lang attribute, the default is:
      htmlTag: document.documentElement
    }
  });

反应形式:

handleChange = (event) =>  {
    const name = event.target.name;
    const value = event.target.value;
    this.setState(prevstate => {
      const newState = { ...prevstate };
      newState[name] = value;
      return newState;
    });
  } 

render() {
   const { t } = this.props;
   return (
     <>
        <form onSubmit={(e) => this.newObjectHandler(e)}>
          <p>
              <label htmlFor="name">{t("Name")}: </label>
              <input
                type="text"
                name="name"
                minLength="6"
                maxLength="40"
                value={this.state.name}
                onChange={this.handleChange}
                required
              />
          </p>
          <p>
              <label htmlFor="count">{t("Count")}: </label>
              <input
                type="number"
                name="count"
                min="0"
                max="100"
                step="1"
                value={this.state.count}
                onChange={this.handleChange}
                required
              />
          </p>
          <p>
          <input type="submit" value={t("New object")} />
          </p>
        </form>
     </>
   )
 }
4

1 回答 1

0

从您的图片看起来您正在使用本机浏览器错误消息

为了翻译它们,您可以使用setCustomValidity.

它看起来像这样:

render() {
  const { t } = this.props;
  return (
    <>
      <form onSubmit={e => this.newObjectHandler(e)}>
        <p>
          <label htmlFor="name">{t('Name')}: </label>
          <input
            type="text"
            name="name"
            minLength="6"
            maxLength="40"
            value={this.state.name}
            onChange={this.handleChange}
            data-message={t('YOUR_MESSAGE_KEY_HERE')}
            onInvalid={this.handleValidity}
            required
          />
        </p>
        <p>
          <label htmlFor="count">{t('Count')}: </label>
          <input
            type="number"
            name="count"
            min="0"
            max="100"
            step="1"
            value={this.state.count}
            onChange={this.handleChange}
            data-message={t('YOUR_MESSAGE_KEY_HERE_2')}
            onInvalid={this.handleValidity}
            required
          />
        </p>
        <p>
          <input type="submit" value={t('New object')} />
        </p>
      </form>
    </>
  );
};

handleValidity = ({target}) => {
  const message = target.dataset.message;
  target.setCustomValidity(message);
}

我在属性上添加了一条翻译的消息data-message,然后在其上附加了 onInvalid 事件,并在其上input触发setCustomValidity了该消息。

于 2019-08-14T13:06:20.247 回答