【问题标题】:React i18n break lines in JSON String在 JSON 字符串中反应 i18n 换行符
【发布时间】:2018-02-02 00:11:08
【问题描述】:

我正在与 i18next 合作以响应 https://github.com/i18next/react-i18next。我正在努力在我的 JSON 语言文件中的字符串中换行。

这是我已经尝试过的,不会换行:

  • line: "This is a line. \n This is another line. \n Yet another line",
  • line: ("This is a line."+ <br/> + "This is another line. \n Yet another line"),
  • line: ('This is a line. <br/> This is another line. \n Yet another line'),

我显然会尝试在每个句子之后换行。我是这样称呼它的:

<TooltipLink onClick={() => {
    this.toggleHelpTextDialog(t('test:test.line'));
}}/>

有什么想法吗?谢谢!

【问题讨论】:

  • 这完全取决于组件。它可能支持也可能不支持换行符。您是否尝试过直接设置文本而不使用 i18n 翻译?
  • 我确实直接设置了文本,它也不起作用。我正在通过道具设置对话框的文本。您认为这可能会导致问题吗?
  • 看看这个问题,可能对你有帮助:stackoverflow.com/questions/2392766/multiline-strings-in-json
  • 我认为这在 i18n 库中应该很简单。

标签: html json reactjs i18next


【解决方案1】:

您可以在翻译文本中使用 css white-space: pre-line;\n

const root = document.getElementById('root');

i18next.init({
  lng: 'en',
  resources: {
    en: {
      translation: {
        "key": "Hello world\nThis sentence should appear on the second line"
      }
    }
  }
}, function(err, t) {
  // initialized and ready to go!
  root.innerHTML = i18next.t('key');
});
#root {
  white-space: pre-line;
}
<script src="https://unpkg.com/i18next@15.0.9/dist/umd/i18next.min.js"></script>

<div id="root"></div>

【讨论】:

  • 在我的例子中,json-editor BabelEdit 将\n 转义为\\n
  • 我对 BabelEdit 不熟悉,但换行符(按 Enter 时创建的)不是在编辑器中写 \n 而是按 Enter。
  • 在 2022 年工作得非常好。谢谢
【解决方案2】:

例如,您在 JSON 语言文件中编写以下文本。

文本:“你好\n你好吗?\n你在做什么?”

然后作为回报部分写

<div id='app'><div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<script>
      render() {
          return (
              text.split('\n').map(c => {
                  return ( <p> {c} </p>) 
                   });
                 )
               }
              

              ReactDOM.render(
                <BreakLine / >
                document.getElementById('app')
              )
</script>

好吧,当调用 split 方法时,尝试创建列表并与 '\n' 分开,并在段落中使用方法映射类型,以便可以换行 ;))

【讨论】:

  • 嗨,欢迎来到 StackOverflow。请您澄清一下您的答案,描述性文字很难理解。
【解决方案3】:

您也可以使用非常容易做到的 CSS:

CSS:

#root {
  white-space: pre-line;
}

HTML:

<script src="https://unpkg.com/i18next@15.0.9/dist/umd/i18next.min.js"></script>

<div id="root"></div>

它将翻译JSON中的\n解释为换行!!!

【讨论】:

    【解决方案4】:

    &lt;br /&gt; 是正确的方法,但它不会进入文本或翻译。示例:

    <div>
      {'my text line 1'}
      <br />
      {'my text line 2'}
    </div>
    

    但是,如果您想在文本中保留换行符 (\n),请使用 dangerouslySetInnerHTML 这样做:

    const text = "This is a line. \n This is another line. \n Yet another line";
    <div dangerouslySetInnerHTML={text} />
    

    【讨论】:

    • 不幸的是,我不能这样做,因为我不仅要设置字符串,还要设置整个组件。不过还是谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 2017-09-05
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2020-09-25
    • 2015-11-19
    相关资源
    最近更新 更多