首页 > 解决方案 > 你如何在 React 字符串中添加换行符?

问题描述

我有一个以字符串形式读取的文本文件,然后像这样插入到 DOM 中:

//the state gets set with the contents of a text file that has proper indentation
  state = {
    parsedText: null
  }
//in the render function, this is how the text comes in
<p>{this.state.parsedText}</p>

当我遍历字符代码时,我可以看到当我 console.log 文件时“输入”代码(即 13)似乎有效(缩进看起来正确)。不幸的是,这些字符代码不能转换为 HTML——整个字符串只是作为一个坚实的文本块出现。所以,我想要做的是插入<br>标签或\n字符,或者&nbsp;为了使中断在 HTML 中起作用。

看起来是这样的:

rawFile.onreadystatechange = () => {
    if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
            let allText = rawFile.responseText;
            for (let i = 0; i < allText.length; i++) {
              let uni = allText.charCodeAt(i)
              if (uni === 13) {
                console.log('enter!!')
                allText = allText.substring(0, i) + "\n" + allText.substring(i + 1, allText.length - 1)
              }
            }
            console.log("allText: ", allText);
            console.log(typeof allText)
            this.setState({
                parsedText: allText
            });
        }
    }
};
rawFile.send(null);

}

\n插入显示在文本字符串中,但在 DOM 中似乎只是被忽略了。有没有办法使这项工作?我已经尝试过危险的SetInnerHTML,但什么也没做。

关于如何使这项工作的任何想法?

标签: javascriptreactjs

解决方案


有同样的问题。刚刚解决了。

您需要做的就是将字符串保存为数组。像这样:

let text = "this is text without break down \n this won't work but will be one line"

let text = ["this is text with breakdown",
 <br/>,
 "this is the second line"];

希望有帮助


推荐阅读