你如何在 React 字符串中放置换行符?

you*_*ter 0 javascript reactjs

我有一个文本文件,我将它作为字符串读取,然后像这样插入到 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>
Run Code Online (Sandbox Code Playgroud)

当我遍历字符代码时,我可以看到当我 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);
Run Code Online (Sandbox Code Playgroud)

}

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

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

小智 5

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

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

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"];
Run Code Online (Sandbox Code Playgroud)

希望有帮助


you*_*ter -1

所以你需要危险地SetInnerHTML,正如FrV所指出的,答案是插入一个<br />...结果我错过了结尾的“/”。哎呀。希望这可以帮助遇到类似问题的人。