如何用React I18Next翻译formik errormessage

发布于 2025-02-05 07:51:54 字数 2132 浏览 1 评论 0原文

我有以下组件:

import { Formik, Form, useField, ErrorMessage } from "formik";
import * as Yup from "yup";
import Select from "react-select";

const iceCreamOptions = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

const FormSelect = ({ name, options }) => {
  const [field, meta, helpers] = useField(name);
  return (
    <>
      <Select
        name={name}
        value={field.value}
        onChange={(value) => helpers.setValue(value)}
        options={options}
        onBlur={() => helpers.setTouched(true)}
      />
      <ErrorMessage name={name} />
    </>
  );
};

const initialValues = {
  icecream: null
};

const validationSchema = Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    })
    .required("Please select a value")
    .nullable()
});

export default function App() {
  return (
    <Formik
      initialValues={initialValues}
      onSubmit={(values) => console.log(values)}
      validationSchema={validationSchema}
    >
      {(props) => {
        return (
          <Form>
            <FormSelect name="icecream" options={iceCreamOptions} />
          </Form>
        );
      }}
    </Formik>
  );
}

现在,我想在我的应用程序中添加一个板,因此我将使用React I18Next。 基本示例就是这样:

const { t } = useTranslation();

<p>{t('message')}</p>

现在,如何将这些翻译与我的错误组件一起使用? 我确定,我不能这样做:D

t(<ErrorMessage name={name} />)

因此,如果无法使用terrormessage来处理它,我认为我需要做以下操作:

{meta.touched && meta.error ? (
  <div className="error">{t(meta.error)}</div>
) : null}

I have following components:

import { Formik, Form, useField, ErrorMessage } from "formik";
import * as Yup from "yup";
import Select from "react-select";

const iceCreamOptions = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

const FormSelect = ({ name, options }) => {
  const [field, meta, helpers] = useField(name);
  return (
    <>
      <Select
        name={name}
        value={field.value}
        onChange={(value) => helpers.setValue(value)}
        options={options}
        onBlur={() => helpers.setTouched(true)}
      />
      <ErrorMessage name={name} />
    </>
  );
};

const initialValues = {
  icecream: null
};

const validationSchema = Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    })
    .required("Please select a value")
    .nullable()
});

export default function App() {
  return (
    <Formik
      initialValues={initialValues}
      onSubmit={(values) => console.log(values)}
      validationSchema={validationSchema}
    >
      {(props) => {
        return (
          <Form>
            <FormSelect name="icecream" options={iceCreamOptions} />
          </Form>
        );
      }}
    </Formik>
  );
}

Now I would like to add tranlations to my application, so i will use React i18next.
Basic example is something like that:

const { t } = useTranslation();

<p>{t('message')}</p>

Now, How can i use this translations with my ErrorMessage component?
I am sure, I can't do something like that :D

t(<ErrorMessage name={name} />)

So if there is no way to handle it with t and ErrorMessage, I think I need to do following thing:

{meta.touched && meta.error ? (
  <div className="error">{t(meta.error)}</div>
) : null}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏见 2025-02-12 07:51:54

您可以像这样使用yup.typeerror()。

    const validationSchema = Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    }).TypeError(' Your msg translated here')
    .required("Please select a value")
    .nullable()
});

You can use Yup.typeError() like this.

    const validationSchema = Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    }).TypeError(' Your msg translated here')
    .required("Please select a value")
    .nullable()
});
甲如呢乙后呢 2025-02-12 07:51:54

我认为您可以直接翻译verionationschema这样。

const validationSchema = (t) => Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    })
    .required(t("RequiredValueTranslation"))
    .nullable()
});

并使用它

const [t] = useTranslation()
const schema = () => validationSchema(t)

I think you can directly translate the validationSchema like this;

const validationSchema = (t) => Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    })
    .required(t("RequiredValueTranslation"))
    .nullable()
});

and use it

const [t] = useTranslation()
const schema = () => validationSchema(t)
小ぇ时光︴ 2025-02-12 07:51:54

另一种方法是从for formik中使用函数,但是以相同的方式,您必须将yup消息更改为翻译钥匙。

errormessage-render

const validationSchema = Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    })
    .required("requiredTranslationKey")
    .nullable()
});

然后,在组件主体中

<ErrorMessage name={name} render={key => t(key)} />

Another approach would be to use the render function from formik, but in the same way you would have to change the yup message to be the translation key.

ErrorMessage-render

const validationSchema = Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    })
    .required("requiredTranslationKey")
    .nullable()
});

and then, in the component body

<ErrorMessage name={name} render={key => t(key)} />

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文