乐闻世界logo
搜索文章和话题

How to render a multi-line text string in React

1个答案

1

In React, there are multiple approaches to render multi-line text strings. Here are several common methods:

1. Using Template Literals

In 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:

jsx
const multiLineText = `Line 1 text Line 2 text Line 3 text`; function App() { return <div>{multiLineText}</div>; }

This approach is straightforward and easy to understand, making it ideal for simple multi-line text without complex logic or tags.

2. Using Arrays

If 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 <div> or <p> tag to ensure lines appear on separate lines. For example:

jsx
const lines = [ "Line 1 text", "Line 2 text", "Line 3 text" ]; function App() { return ( <div> {lines.map((line, index) => ( <div key={index}>{line}</div> ))} </div> ); }

This method allows you to easily apply styles or execute JavaScript logic per line.

3. Using CSS Styles

Control text display using CSS. Pass the entire text as a string in JSX and use the CSS white-space property to preserve line breaks. Set white-space: pre-wrap; to maintain all whitespace and line breaks from the source text. For example:

jsx
const multiLineText = "Line 1 text\nLine 2 text\nLine 3 text"; function App() { return ( <div style={{ whiteSpace: "pre-wrap" }}> {multiLineText} </div> ); }

pre-wrap preserves line breaks and whitespace while automatically wrapping long text.

Summary

The 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.

2024年6月29日 12:07 回复

你的答案