【问题标题】:get same value from multiple select dropdown in react js从反应js中的多个选择下拉列表中获取相同的值
【发布时间】:2021-12-20 01:23:33
【问题描述】:

我不会喜欢这样的。我有一个篮子,这里有五个苹果。我想把它分成五个人。如果用户从这里拿了 2 件物品。然后下一个人必须有 3 件物品。如果这个人拿了 2 件物品,那么篮子里只有 1 件物品。五个用户会像

<select>
  <label>userOne</label>
  <option>0</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>;
{
  /* userOne selected 2 */
}
<select>
  <label>userTwo</label>
  <option>0</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  {/* removed automaticaly 4 and five option */}
  {/* <option>4</option>
        <option>5</option> */}
</select>;
{
  /* userTwo select 2 */
}
<select>
  <label>userThree</label>
  <option>0</option>
  <option>1</option>
  {/* <option>2</option>
        <option>3</option> */}
  {/* 3-2 = 1 */}
</select>;
{
  /* userFour have only one  */
}
<select>
  <label>userFour</label>
  <option>0</option>
  <option>1</option>
  {/* <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option> */}
</select>;
{
  /* userFour already selected one */
}
<select>
  <label>userFive</label>
  <option>0</option>
  {/* userFive have no item available */}
  {/* <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option> */}
</select>;

【问题讨论】:

  • 欢迎堆栈溢出!请记住包含Minimal, Complete, and Verifiable 示例。比如你到目前为止尝试过什么,失败了什么,你做了什么研究。

标签: reactjs select dropdown


【解决方案1】:

据我了解,您希望根据所选数据过滤选项列表
为此,您需要动态显示选项。
此类代码示例:

import React, { useState } from "react";

const USER_COUNT = 5;
const OPTION_COUNT = 5;
const options = Array(OPTION_COUNT + 1)
  .fill(0)
  .map((_, i) => i);

function App() {
  let [users, setUsers] = useState(Array(USER_COUNT).fill(0));

  const handleChange = (idx) => (e) => {
    setUsers(
      users.map((user, userIdx) => {
        if (userIdx < idx) {
          return user;
        }
        if (userIdx === idx) {
          return +e.target.value;
        }
        return 0;
      })
    );
  };

  return (
    <div className="App">
      {users.map((user, userIdx) => {
        let prevOptionsSum = 0;
        for (let i = 0; i < userIdx; i++) {
          prevOptionsSum += users[i];
        }
        let userOptions = options.slice(0, options.length - prevOptionsSum);
        return (
          <div key={userIdx}>
            <label>user {userIdx + 1}</label>
            <select value={user} onChange={handleChange(userIdx)}>
              {userOptions.map((_, userOptionIdx) => (
                <option key={userOptionIdx}>{userOptionIdx}</option>
              ))}
            </select>
          </div>
        );
      })}
    </div>
  );
}
export default App;

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2019-04-18
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多