您可以使用white-space
css属性并将其设置为pre
个、pre-line
个或pre-break
等值,具体取决于您希望文本的行为方式,以保留空白.
以下是2023-08-11年的MDN docs on white-space
个国家的节选.
值
white-space
属性值可以指定为从下面的值列表中 Select 的单个关键字,也可以指定为表示white-space-collapse
和text-wrap
属性速记的两个值.
normal
个
- :空白的序列被折叠.源中的换行符与其他空白字符的处理方式相同.根据需要断开线条以填充线条框.
nowrap
个
- : Collapses white space as for
normal
个, but suppresses line breaks (text wrapping) within the source.
pre
个
- :保留了空白序列.只在源代码中的换行符和
<br/>
个元素处换行.
pre-wrap
个
- :保留了空白序列.换行符、
<br/>
和填充行框所需的行断开符.
pre-line
个
- :空格的序列被折叠.换行符、
<br/>
和填充行框所需的行断开符.
break-spaces
个
|
New lines |
Spaces and tabs |
Text wrapping |
End-of-line spaces |
End-of-line other space separators |
normal 个 |
Collapse |
Collapse |
Wrap |
Remove |
Hang |
nowrap 个 |
Collapse |
Collapse |
No wrap |
Remove |
Hang |
pre 个 |
Preserve |
Preserve |
No wrap |
Preserve |
No wrap |
pre-wrap 个 |
Preserve |
Preserve |
Wrap |
Hang |
Hang |
pre-line 个 |
Preserve |
Collapse |
Wrap |
Remove |
Hang |
break-spaces 个 |
Preserve |
Preserve |
Wrap |
Wrap |
Wrap |
有关HTML和空格的更多详细信息,请参阅MDN - How whitespace is handled by HTML, CSS, and in the DOM.
// copied from the question
const textWithWhiteSpace = `to stay new and fresh even after over four decades in the business.
Downey was born April 4, 1965 in Manhattan, New York....`;
function App({ text }) {
return <p className="biography">{text}</p>;
}
ReactDOM.render(<App text={textWithWhiteSpace} />, document.getElementById("root"));
.biography {
font-size: 1.4rem;
color: #333333;
text-align: justify;
/* preserve whitespace */
white-space: pre;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>