不能将<Text />节点用作对象上的转换字符串

Agu*_*ani 3 javascript internationalization preact

在我目前正在工作的项目上,我们需要支持多种语言,因此我们最终使用了preact -helmet来为每个App视图注入标题和相应的元标记,但是我无法使其与{{fields}}占位符一起使用,所以我创建了这个示例项目来演示该问题。

如何安装和运行示例项目

  • 克隆仓库 git clone git@github.com:acangiani/preact-i18n-issue.git
  • 安装依赖项: npm install
  • 运行项目 npm run start

第一视角

这可以正常工作,并正确添加标题和标题元标记。

这样做curl http://localhost:3000/,将输出以下html:

...
<title>Foo - Bar</title>
<meta name="title" content="Foo - Bar" data-preact-helmet="true">
...
Run Code Online (Sandbox Code Playgroud)

第二种观点

另一方面,在此视图上,我需要使用一个{{field}}占位符,这样做curl http://localhost:3000/test,将输出以下html:

...
<title>test - Bar</title>
<meta name="title" content="[object Object]" data-preact-helmet="true">
...
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情

  1. 使用@withText作为第二视图修饰,但我不能访问该道具。
  2. 试图withText用作功能组件包装器,以便获取翻译后的文本,但我无法使其正常工作。
  3. 尝试将组件渲染为类似以下的字符串:
render(<Text id="second.title" " fields={{ field: props.slug }}>default text</Text>)
Run Code Online (Sandbox Code Playgroud)

但无论加载在上的i18n定义如何,我都只获得默认文本IntlProvider

最重要的是,我需要以字符串形式获取翻译后的文本,但我无法做到这一点,请您提供帮助吗?

Agu*_*ani 5

如前所述这里,这是正确的解决方案:

@withText((props) => ({
  title: <Text id="second.title" fields={{ field: props.slug }} />
}))
export default class SecondView extends Component {
  render(props, state) {
    return (
      <div>
        <Helmet
          title={props.title}
          meta={[
            {name: "title", content: props.title },
          ]}
        />
      </div>
    );
  }
};
Run Code Online (Sandbox Code Playgroud)