首页 > 解决方案 > 在 react.js 下拉列表中添加自定义选项以及如何填充

问题描述

react.js 的新手,正在做一个项目。

我的 jsx 文件是这样的:

const myFunction= () => {
...
declaring the data in variable called statuses
...
  return (
    <>
      <h4>Show statuses</h4>
      <div className="float-left">
        Filter
        <Dropdown
          optionLabel="value"
          optionValue="key"
          options={statuses}
          filterBy="value"
          filter
          showClear
        />
      </div>
    </>
  );
}

状态中的数据显示如下:

[
  {
    "key": 1,
    "text": "Status 1",
    "value": "Status 1"
  },
  {
    "key": 2,
    "text": "Status 2",
    "value": "Status 2"
  },
 ]

我得到的结果是这样的:

    <ul class="p-dropdown-items" role="listbox">
<li class="p-dropdown-item" aria-label="Status 1" role="option" aria-selected="false">Stlatus 1</li>
<li class="p-dropdown-item" aria-label="Status 2" role="option" aria-selected="false">Status 2</li>
</ul>

我的问题是:

  1. 如何在 statuses 变量之前的下拉列表中插入自定义选项?我想要一个自定义选项,即 value='0' label='All'。
  2. 为什么生成的 html 代码中没有显示每个下拉项的值?我错过了什么还是我需要不同的语法?

谢谢大家

标签: reactjs

解决方案


您可以在 jsx 中映射您的数组并使用适当的道具返回 Dropdown 元素,如下所示:

{data.map((obj) => {
   return (
      <Dropdown
          key={obj.key} // should be added
          optionLabel={obj.text}
          optionValue={obj.value}
          options={statuses}
          filterBy={obj.value}
          filter
          showClear
        />
   )
})}

推荐阅读