问题答案 12026年6月22日 07:45
How to render a multi-line text string in React
In React, there are multiple approaches to render multi-line text strings. Here are several common methods:1. Using Template LiteralsIn JSX, you can utilize ES6 template literals (also known as template strings) to embed variables or expressions. When displaying multi-line text, leverage the natural line breaks within template literals. For example:This approach is straightforward and easy to understand, making it ideal for simple multi-line text without complex logic or tags.2. Using ArraysIf each line requires specific styling or processing, treat each line as an element in an array and iterate over it in JSX. Wrap each element in a or tag to ensure lines appear on separate lines. For example:This method allows you to easily apply styles or execute JavaScript logic per line.3. Using CSS StylesControl text display using CSS. Pass the entire text as a string in JSX and use the CSS property to preserve line breaks. Set to maintain all whitespace and line breaks from the source text. For example: preserves line breaks and whitespace while automatically wrapping long text.SummaryThe choice depends on specific requirements. For simple multi-line display, template literals are the simplest approach. For complex per-line processing or styling, arrays are more suitable. The CSS method is ideal for controlling line breaks and whitespace in long text. Each method has appropriate use cases, and you can choose flexibly based on the situation.