Solve the problem of not recognizing spaces and line breaks in text and string display

Preface: In daily development, we often encounter input boxes or text displays that require the text or string to maintain its original format. The focus includes the issues of leading and trailing spaces and line breaks in the middle. When displaying text directly in React, the leading and trailing characters will be removed directly. Issues with spaces and line breaks.

In normal development, it is occasionally necessary to use leading and trailing spaces or line breaks to occupy spaces to simply and crudely improve formatting issues.

Example:

 1. Simple text display. The code only displays the effect.

<div>    文本显示   格式如下    </div>    
// 实际输出 '文本显示    格式如下'
// 想要的效果 '    文本显示    格式如下    '

2. Display of variables

const  a='    艾欧尼亚!
                 昂扬不灭!
                    洛克萨斯即将崛起!'
 <div>{a}</div>  
 //实际输出   '艾欧尼亚!昂扬不灭!洛克萨斯即将崛起!'  
 //想要的效果  '    艾欧尼亚!
                 昂扬不灭!
                    洛克萨斯即将崛起!' 

Many of the implemented effects will be ignored by the browser.

therefore! ! ! In order to solve this problem, we only need to add a style attribute to his box to complete the effect display.

white-space: pre-wrap;//解决 React 中的字符串不识别换行和多个空格的问题。

If you successfully helped solve the problem, remember to come back and give it a like!

Introduction to extended attributes: derived from CSS white-space attribute

The white-space attribute sets how whitespace within an element is handled.

white-space attribute

normal

default. White space is ignored by the browser.

pre

White space will be preserved by the browser. It behaves like the <pre> tag in HTML.

nowrap

The text does not wrap; the text continues on the same line until a <br> tag is encountered.

pre-wrap

Whitespace sequences are preserved, but newlines are wrapped normally.

pre-line

Merge whitespace sequences but preserve newlines.

you inherit

Specifies that the value of the white-space attribute should be inherited from the parent element.

Guess you like

Origin blog.csdn.net/youyudehan/article/details/128328031