简体   繁体   English

如何在 const 字符串中包含换行符/换行符?

[英]How to have newlines/line breaks within a const string?

I have a string declared as a const in React JS.我在 React JS 中有一个声明为 const 的字符串。 And I am trying to display it but the appropriate newlines/line breaks aren't not working properly.我正在尝试显示它,但适当的换行符/换行符无法正常工作。 I tried putting \\n within the string itself but it doesn't work and I'm hoping to get some help.我尝试将 \\n 放在字符串本身中,但它不起作用,我希望得到一些帮助。

The String Variable itself字符串变量本身

const CODE_EXAMPLE = `
const CHECKBOX = {
LABEL: {
    content: SECONDARY_GLOBAL_TEXT,
    disabled: {
      content: SECONDARY_GLOBAL_DISABLED_TEXT
    }
  },
  ERROR_MESSAGE: {
    content: SECONDARY_GLOBAL_ERROR_TEXT
  },
  checked: {
    icon: PRIMARY_GLOBAL_BASE,
    background: TRANSPARENT,
    hover: {
      icon: PRIMARY_GLOBAL_BASE,
      background: SECONDARY_GLOBAL_HOVER,
    },
    disabled: {
      icon: SECONDARY_GLOBAL_DISABLED_CONTENT
    }
  },
}
`;

How I am rendering it我如何渲染它

<div className="gray-background">
  {CODE_EXAMPLE} 
</div>

This is what it currently looks like:这是它目前的样子:

在此处输入图片说明

This is what it's supposed to look like:这应该是这样的:

在此处输入图片说明

This is an HTML feature, it collapses any extra spaces/new lines by default.这是一个 HTML 功能,默认情况下它会折叠任何额外的空格/新行。 You can use tag pre to see the text as is.您可以使用标签pre原样查看文本。

You may be able to accomplish this through css via white-space: pre您可以通过 css 通过white-space: pre来完成此操作white-space: pre

This post goes over some options. 这篇文章介绍了一些选项。

\\n will not work in JSX. \\n 在 JSX 中不起作用。 In this case, I would suggest splitting the lines used with special characters.在这种情况下,我建议拆分使用特殊字符的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM