【问题标题】:How to use i18next / react-i18next inside MDX / Markdown files with MDXJS?如何在带有 MDXJS 的 MDX / Markdown 文件中使用 i18next / react-i18next?
【发布时间】:2020-09-10 21:20:45
【问题描述】:

我们使用 MDXJS 包在 Markdown 中编写内容并在其中使用 React 组件。

有没有办法在 MDX / Markdown 文件中使用 i18next / react-i18next 包?

【问题讨论】:

标签: reactjs next.js i18next react-i18next mdxjs


【解决方案1】:

? 在MDX 中使用i18next

当你导入 MDX 文件时,你只需将它用作任何其他 React 组件:

import { default as SomeContent } from './some-content.mdx';

...

<SomeContent />

因此,你也可以传递一些 props,在本例中为 t 函数,并在内部以一些特定的方式使用它:

import { default as SomeContent } from './some-content.mdx';

export const SomeComponent: React.FC = React.memo((props) => {
  const { t } = useTranslation();

  return (
    <SomeContent t={ t } someProp="Some value" />
  );
});

如果您想检查这是否有效或查看您的 MDX 文件中可以访问哪些道具,请将其添加到其中:

<pre>{ JSON.stringify(props, null, '  ') }</pre>
<pre>{ typeof props.t }</pre>

对于上面的例子,它会显示:

{"someProp":"Some value"}
function

请注意,您不能在“原始”MD 元素中使用这些道具,即使您在它们周围添加了包装器:

### Doesn't work: { props.t('some.translation') }

Doesn't work: { props.t('some.translation') }.

Doesn't work: <>{ props.t('some.translation') }</>.

Doesn't work: <Fragment>{ props.t('some.translation') }</Fragment>.

Doesn't work: <span>{ props.t('some.translation') }</span>.

所以你必须改写HTML标签:

<h3>Works: { props.t('some.translation') }</h3>

<p>Works: { props.t('some.translation') }.</p>

<p>Works: <>{ props.t('some.translation') }</>.</p>

<p>Works: <Fragment>{ props.t('some.translation') }</Fragment>.</p>

<p>Works: <span>{ props.t('some.translation') }</span>.</p>

? 在i18next 中使用MDX

如果您在i18next 配置中设置returnObjects: true,您还可以在翻译文件中添加MDX 组件:

import { default as ContentEN } from './content.en.mdx';
import { default as ContentES } from './content.es.mdx';

i18next.use(initReactI18next).init({
  resources: {
    en: {
      translation: {
        content: ContentEN,
      },
    },
    es: {
      translation: {
        content: ContentES,
      },
    },
  },

  returnObjects: true,
}));

然后你可以在你的任何组件中使用它(是的,你也可以像以前一样传递t 或任何其他道具:

export const SomeComponent: React.FC = React.memo((props) => {
  const { t } = useTranslation();
  const Content = t('content');

  return (
    <Content t={ t } someProp="Some value" />
  );
});

? 在@mdx-js/runtime 中使用i18next

如果您使用@mdx-js/runtime,那么您将传递您的道具为scope

import { default as SomeContent } from './some-content.mdx';

export const SomeComponent: React.FC = React.memo((props) => {
  const { t } = useTranslation();

  return (
    <MDX components={ ... } scope={ { t, someProp: 'Some value' } }>{ props.mdx }</MDX>
  );
});

【讨论】:

    猜你喜欢
    • 2019-07-13
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2021-05-12
    • 2020-07-12
    相关资源
    最近更新 更多