React Native 是的,不能与i18n正常工作

nsc4cvqm  于 2023-02-16  发布在  React
关注(0)|答案(4)|浏览(189)

我有这样一段代码。我想根据用户的区域设置添加错误消息,但是会抛出错误,如果字段填写不正确也会抛出错误
[缺少“en.login.emailRequiredError”翻译] [缺少“en.login.passRequiredError”翻译]

const schema = yup.object().shape({
  email: yup
      .string()
      .email(i18n.t('login.emailSpellError'))
      .required(i18n.t('login.emailRequiredError')),
  password: yup
      .string()
      .matches(/^((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15})$/i, i18n.t('login.passSpellError'))
      .required(i18n.t('login.passRequiredError')),
});

i18n.t('login. passRequiredError')在我把它放到一个render方法中检查时工作正常,但在yup中不工作。有什么建议吗?提前感谢

sqxo8psd

sqxo8psd1#

在架构中,替换:

.email(i18n.t('login.emailSpellError'))

.email('login.emailSpellError')

然后在你的render方法中

{t(`form.errors.${form.errors.email}`)}

这假定您的翻译文件有一个如下所示的条目:

"form": { "errors": {"login": {"emailSpellError": "Your email is invalid"}}}}

这里的目标是将t()方法移动到render方法中,并在那里进行所有转换。

prdp8dxp

prdp8dxp2#

是验证方法

// You define the key mentioned in the translation file, in my example 'Invalid email' and 'Required'  

    let ForgotPasswordSchema = yup.object().shape({
      email: yup.string().email('Invalid email').required('Required'),
    });

在render方法中,

// As per your definition

isInvalid={(!!errors.email) && this.context.t(!!errors.email)}
invalidText={(errors.email) && this.context.t(errors.email)}

转换文件

export const translations = {
  "cy": {
    "Required":"Gofynnol",
    "Invalid email":"Nid yw'r cyfeiriad ebost yn ddilys",
}
 };
8ulbf1ek

8ulbf1ek3#

一个解决方案是创建一个返回验证模式的函数,然后在组件中调用该函数并存储结果,这样就可以保证验证消息的翻译是动态计算的。
这里的另一个优势是您可以在消息源进行翻译。

// Translation file
{
  "validation.invalid-email": "Email is invalid",
  "validation.field-required": "Field is required"
}

// Validation schema
const forgotPasswordSchema = () => {
  return yup.object().shape({
    email: yup
      .string()
      .email(i18n.t('validation.invalid-email'))
      .required(i18n.t('validation.field-required')),
  });
};

// Your component
const FormComponent = () => {
  const schema = useMemo(() => forgotPasswordSchema(), [i18n.language]); // NB: `[i18n.language]` is optional and `[]` will suffice depending on how you're handling language change

  return <>...</>;
}
gajydyqb

gajydyqb4#

我已经为这种方法创建了一些自定义钩子
这一个用于在更改应用程序语言时刷新架构内的错误消息

import { yupResolver } from '@hookform/resolvers/yup';
import { useRouter } from 'next/router';
import { useMemo } from 'react';

const useSchema = (getSchema) => {
  const { locale } = useRouter();
  const resolver = useMemo(getSchema, [locale]);

  return yupResolver(resolver);
};

export default useSchema;

这一项用于在应用程序组件本地化错误消息中设置全局

import { useTranslation } from 'react-i18next';
import { setLocale } from 'yup';

export const useLocalisedYupSchema = () => {
  const { t } = useTranslation('common');

  setLocale({
    mixed: {
      required: t('validation.required')
    },
    string: {
      min: ({ min }) => t('validation.min', { min }),
      max: ({ max }) => t('validation.max', { max })
    },
  });
};

还使用了组件内部的架构和React Hook Form

import { getChangePasswordSchema } from 'static/schemas/changePassword';
import useSchema from 'utils/hooks/useSchema';
import { useForm } from 'react-hook-form';

const AccountContentSecurity = () => {
  ...
  const resolver = useSchema(getChangePasswordSchema);
  const { reset, control, handleSubmit } = useForm({
    defaultValues: {
      'current_password': '',
      'new_password': '',
      'password_confirmation': '',
    },  
    resolver,
  });
  ...

和模式

import { passwordSchema } from 'static/schemas';
import { object } from 'yup';

export const getChangePasswordSchema = () => object({
  'current_password': passwordSchema,
  'new_password': passwordSchema,
  'password_confirmation': passwordSchema,
});

相关问题