使用 i18next 将变量替换为 ReactNode 元素

Sis*_*sky 5 javascript internationalization typescript i18next reactjs

我有一个翻译 json 文件,其翻译如下:

"pageNotFound": {
  "description": "The page could not be found. Click {{link}} to return to the home page"
},
Run Code Online (Sandbox Code Playgroud)

我想要替换的链接变量ReactRouter <Link>

我的方法中有以下代码render,输出下图。

public render() {

  const { t } = this.props;
  const message = t('pageNotFound.description', { link: <Link to="/">here</Link> });

  return (
    <div className="body-content">
      <div>
        {message}
      </div>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

翻译空

我已经使用过该<Trans>组件,我认为这可能是一种方法,但似乎您必须输入包括 <> 标签的全文,这对于我的用例来说不是我想要的,因为我希望所有文本都在如果可能的话,翻译 json。

有什么建议欢迎留言

fel*_*osh 6

您应该Trans为此使用组件。

"pageNotFound": {
  "description": "The page could not be found. Click <0>here</0> to return to the home page"
},
Run Code Online (Sandbox Code Playgroud)
public render() {
  const { t } = this.props;

  return (
    <div className="body-content">
      <div>
        <Trans
          t={t}
          i18nKey="pageNotFound.description"
          components={[
            <Link key={0} to="/">
              here
            </Link>,
          ]}
        />
      </div>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)