P粉8934570262023-09-04 17:19:03
您可以迭代映射方法,只要遇到任何“/n”就將其拆分。此外,您也可以為此目的建立一個有序清單。例如,找到下面的程式碼。
import React from 'react'; const items = "\n1. apple\n2. mango"; const ListComponent = () => { const itemList = items.split('\n').map((item, index) => { const trimmedItem = item.replace(/^\d+\.\s/, ''); if (item.trim()) { return <li key={index}>{ trimmedItem}</li>; } return null; }); return ( <div> <p>Here is the list:</p> <p>These are the items:</p> <ol>{itemList}</ol> </div> ); }; export default ListComponent;
這是上面程式碼運行時的螢幕截圖 運行上面的程式碼
P粉3767388752023-09-04 16:57:06
您應該用換行符號分割字串,然後將其對應到多個段落標籤
const items = "These are the items:\n1. apple\n2. mango"; // or if you want it t be reactive: const [items, setItems] = useState("These are the items:\n1. apple\n2. mango");
然後在html中:
<div className="list"> {items.split('\n').map((el) => ( <p>{el}</p> ))} </div>
現在清單可以正確顯示,如果項目居中並且您希望它們左對齊,只需輸入 text-align: left;在列表 css 類別中