如何在JSX文件中为displayMessage正确添加换行符?
解决方法
JSX 默认会忽略文本中的\n换行符以及连续空白字符,所以你写的换行符不会在渲染时生效,可通过以下三种方案解决:
方案1:添加CSS样式(推荐,改动最小)
给渲染displayMessage的元素添加white-space: pre-line属性即可,该属性会保留文本中的换行符,同时自动折叠多余空格,适配正常的文本排版需求。
示例代码:
.message-box { white-space: pre-line; }
// 渲染部分代码 <div className="message-box"> {this.state.displayMessage} </div>
方案2:修改状态结构,直接插入换行标签
把displayMessage改成包含文本和<br/>标签的数组,JSX渲染时会自动识别标签实现换行:
handleNotFound() { const url = window.location.href; // 保留你原有获取url的逻辑 this.setState({ displayMessage: [ 'It looks like the link you are trying to reach does not exist.', <br />, 'If you clicked this link , please leave a comment within the article that contained the link so the author can be notified.', <br />, 'If you clicked this link from a location outside of __, please contact the _to open a ticket with the application where this link is referenced .', <br />, 'The link you were trying to reach: ' + url ] }); }
方案3:渲染时拆分文本动态插入换行
如果不想修改原有状态逻辑,可以在渲染时按\n拆分文本,遍历生成带换行的内容:
<div> {this.state.displayMessage.split('\n').map((line, idx) => ( <React.Fragment key={idx}> {line} <br /> </React.Fragment> ))} </div>
内容的提问来源于stack exchange,提问作者rmanshich
相关产品推荐
相关产品推荐

