我想建立 javascript 字串,以便當它在 div 標籤內傳遞時它顯示為列表
P粉478445671
P粉478445671 2023-09-03 23:13:31
0
2
553
<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粉478445671
P粉478445671

全部回覆(2)
P粉893457026

您可以迭代映射方法,只要遇到任何“/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粉376738875

您應該用換行符號分割字串,然後將其對應到多個段落標籤

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!