作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我们使用 MDXJS包以在 Markdown 中编写内容并在其中使用 React 组件。
有没有办法使用 i18next/react-i18next MDX/Markdown 文件中的包?
最佳答案
🌍 使用 i18next
内MDX
:
当您导入 MDX
时文件,你只需将它用作任何其他 React 组件:
import { default as SomeContent } from './some-content.mdx';
...
<SomeContent />
因此,你也可以传递一些 Prop ,在这种情况下是
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" />
);
});
如果您想检查这是否有效或查看哪些 Prop 可以从您的
MDX
中访问文件,在里面添加:
<pre>{ JSON.stringify(props, null, ' ') }</pre>
<pre>{ typeof props.t }</pre>
对于上面的示例,它将显示:
{"someProp":"Some value"}
function
请注意,您不能在“原始”中使用这些 Prop
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>
🧩 使用
MDX
在
i18next
:
returnObjects: true
在您的
i18next
config,你也可以添加
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
或任何其他 Prop ,就像以前一样:
export const SomeComponent: React.FC = React.memo((props) => {
const { t } = useTranslation();
const Content = t('content');
return (
<Content t={ t } someProp="Some value" />
);
});
🏃 使用
i18next
内
@mdx-js/runtime
:
@mdx-js/runtime
,那么你会将你的 Prop 传递为
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>
);
});
关于reactjs - 如何在带有 MDXJS 的 MDX/Markdown 文件中使用 i18next/react-i18next?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53119525/
我们使用 MDXJS包以在 Markdown 中编写内容并在其中使用 React 组件。 有没有办法使用 i18next/react-i18next MDX/Markdown 文件中的包? 最佳答案
我是一名优秀的程序员,十分优秀!