Reactjs 按对象显示选定的选项

Reactjs show selected option by object

我有一个名为 data 的对象并且已经在 select 中显示值 option 现在我想通过 selected 对象显示 selected 选项,但没有成功:

let data = [
  {id: 1, name: 'xxx'},
  {id: 2, name: 'yyy'},
  {id: 3, name: 'zzz'},
  {id: 4, name: 'sss'},
  {id: 5, name: 'vvv'},
];

let selected = [
  {id: 1, name: 'xxx'},
  {id: 3, name: 'zzz'},
  {id: 5, name: 'vvv'},
]


<select multiple={true}>
data.map(function(Creator, index){
  return (
    <option key={Index}>{Creator.name}</option>
  )
});
</select>

我做到了:

{data.map(function(Cr, In){
    {selected.map(function (Creator, Index) {
        return (
            <option selected={Creator.name === Cr.name ? true : false} key={In}>{Cr.name}</option>
        )
    })}
})}

但是 return 没有 option 我想这不是最佳做法,我该如何解决这个问题?什么是最佳做法?

使用函数迭代选项,并使用find检查选项的idname是否与所选对象的相同属性匹配数组,并使用该变量来确定是否应选择该选项。

在这个工作示例中,我已将 options/selected 数据传递到示例组件中,并为方便起见使用选项数据设置状态。

const { useState } = React;

function Example({ data, selected }) {

  const [ options, setOptions ] = useState(data);

  function getSelected() {

    // Iterate over the options, and get the id, and name
    return options.map(option => {

      const { id, name } = option;

      // `found` is a boolean depending on whether the option
      // in the current iteration is in the selected array
      const found = selected.find(obj => {
        return obj.id === id && obj.name === name;
      });

      // And then we can return an option where selected
      // is the result of that boolean, either true or false
      return <option value={option} selected={found}>{name}</option>;
    });
  }

  return (
    <div>
      <select multiple>
        {getSelected()}
      </select>
    </div>
  );
};

const data = [
  {id: 1, name: 'xxx'},
  {id: 2, name: 'yyy'},
  {id: 3, name: 'zzz'},
  {id: 4, name: 'sss'},
  {id: 5, name: 'vvv'},
];

const selected = [
  {id: 1, name: 'xxx'},
  {id: 3, name: 'zzz'},
  {id: 5, name: 'vvv'},
];

ReactDOM.render(
  <Example data={data} selected={selected} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

您可以执行类似这样的操作,这将得到解决方案,但会导致额外的步骤。为了避免 运行 额外的检查步骤,您可以使用字典。

 const addList = data.map(function (Creator, index) {
    let check = false;
    for (let i = 0; i < selected.length; i++) {
      if (selected[i].id == Creator.id) {
        check = true;
        break;
      }
    }
    return (
      <option key={Creator.id} selected={check}>
        {Creator.name}
      </option>
    );
  });

下面是使用字典的

  let newobj = {};

  for(let i=0;i<selected.length;i++){
    newobj[selected[i].id]="selected";
  }

  const addList = data.map(function (Creator, index) {
    return (
      <option key={Creator.id} selected={newobj[Creator.id]==="selected"}>
        {Creator.name}
      </option>
    );
  });

不要迭代选中的对象,像这样通过索引读取它们selected[index]

data.map(function(Creator, index){
  return (
    <option selected={Creator.id === selected[index].id ? true : false}>{Creator.name}</option>
  )
});

这是最快的方法。

您所需要的只是一个使用 .selectedOptions 从下拉列表中获取所选选项的函数,这将 return 您的 HTML 标签中任何时间点的所有所选选项,然后,您可以使用循环将值推入数组以得出您想要的答案。见下文;

export default function App() {

  let data = [
    {id: 1, name: 'xxx'},
    {id: 2, name: 'yyy'},
    {id: 3, name: 'zzz'},
    {id: 4, name: 'sss'},
    {id: 5, name: 'vvv'},
  ];

//function to get selected options
  function getSelected(e){
      var stdOptions = e.target.selectedOptions
      var selected = []
     
//loop to push the selected values into an array
//note that in the HTML sections, important values have been stored in 'id' and 'value' properties, so we can get them here 
      for (var i =0 ; i <stdOptions.length; i++){
        selected.push({
          'id': stdOptions[i].id,
          'name': stdOptions[i].value
        })
      }
      console.log(selected)
  }

  return (
    <div>

      <select  multiple onChange = {getSelected}>
        {data.map((deet, key)=>{
          return (
          <option key = {key} id={deet.id} value={deet.name} > {deet.name} </option>
        )
        })}
      </select>

    </div>
    )
  }