搜索

首页  >  问答  >  正文

我想创建 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粉478445671523 天前662

全部回复(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
  • 取消回复