【问题标题】:How to render a formatted template string in React instead of one paragraph?如何在 React 中呈现格式化的模板字符串而不是一个段落?
【发布时间】:2025-12-24 19:15:11
【问题描述】:

我将状态设置如下 -

setMessage(color, text) {
        this.setState({ message: { color: color, text: text } });
    }

body = `These are your options to raise money:​
Increase your credit allowance (invite new people into the game, this increases your overdraft auto`

this.setMessage('red', `${body}` );

我正在渲染它是 {this.state.message.text},但它不会渲染多行,而是全部被压缩到 一个段落

如何修复并渲染它?

【问题讨论】:

  • HTML 默认会折叠空白。您可以使用 css white-space: pre 保留空格
  • 但是我使用 {this.state.message.text} 渲染它,我该如何设置这个样式?

标签: javascript reactjs string string-literals template-literals


【解决方案1】:

您可以使用 Jsx 来做到这一点。我也遇到过这个问题,我是这样解决的,它确实对我有用。 您可以使用 React 片段标记或任何有效的 jsx 标记

setMessage(color, text) {
        this.setState({ message: { color: color, text: text } });
    }

body = <>These are your options to raise money:​<br />
Increase your credit allowance (invite new people into the game, this increases your overdraft auto</>

this.setMessage('red', body );

【讨论】: