搜尋

首頁  >  問答  >  主體

我想建立 javascript 字串,以便當它在 div 標籤內傳遞時它顯示為列表

<p>我正在嘗試使用 JavaScript 在 <code>div</code> 標籤內顯示包含特定格式的項目清單的字串。該字串包含我想要顯示為項目符號列表的幾個項目。這是範例字串:</p> <pre class="lang-js prettyprint-override"><code>const items = "These are the items:\n1. apple\n2. mango"; </code></pre> <p>我想要格式化字串,使其在 <code>div</code> 標籤內顯示如下:</p> <pre class="brush:php;toolbar:false;">These are the items: 1. apple 2. mango</pre> <p>我正在使用 React 和 Tailwind CSS,這個問題與 React 元件有關。 </p>
P粉478445671P粉478445671517 天前653

全部回覆(2)我來回復

  • P粉893457026

    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;
        
    

    這是上面程式碼運行時的螢幕截圖 運行上面的程式碼

    回覆
    0
  • P粉376738875

    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 類別中

    回覆
    0
  • 取消回覆