【问题标题】:Can <option> has more than one value? using React-hooks [duplicate]<option> 可以有多个值吗?使用 React-hooks [重复]
【发布时间】:2020-07-06 09:16:08
【问题描述】:

我想知道我的选项在反应中是否可以有多个值。

谁能帮助我如何为我的选项增加新的价值?如您所见,“value2”不是正确的方法。

    const handleSelect = e => {
    const { target } = e;
    setAccount(target.value);
    setAccId(target.value2);
  };
  console.log("account", account);
  return (
    <Card width bold>
      New Transaction
      <select
        value={account}
        onChange={e => handleSelect(e)}
        className="transaction__select"
      >
        <option>Choose acc</option>
        {usersAccounts &&
          usersAccounts.map(acc => (
            <option value={acc.accountNumber} value2={acc.id} key={acc.id}>
              {acc.accountNumber}
            </option>
          ))}

我找到了 JSON 的解决方案,以及解决这个问题的其他方法,但我不知道如何在 react 中为我的代码创造更多价值。

【问题讨论】:

标签: reactjs select react-hooks option


【解决方案1】:

这不是反应相关的东西,而是html。 option 元素只能有有效的属性(例如,值、禁用、标签和选择 - 如果我没记错的话,你在 select 元素上使用选择),val2 不是其中之一。

【讨论】:

    【解决方案2】:

    如果您有权访问userAccounts,请将option 值设置为数组中帐户的index。然后使用传递的索引调用setAccountsetAccId。否则,您可以使用data 属性。见https://reactjs.org/blog/2017/09/08/dom-attributes-in-react-16.html

    使用index访问数组

    const handleSelect = e => {
        const { target } = e;
    
        setAccount(userAccounts[target.value].accountNumber);
        setAccId(userAccounts[target.value].id);
      };
      console.log("account", account);
      return (
        <Card width bold>
          New Transaction
          <select
            value={account}
            onChange={e => handleSelect(e)}
            className="transaction__select"
          >
            <option>Choose acc</option>
            {usersAccounts &&
              usersAccounts.map((acc, idx) => (
                <option value={idx} key={acc.id}>
                  {acc.accountNumber}
                </option>
              ))}
    

    使用dataset

    const handleSelect = e => {
        const { target } = e;
        setAccount(target.value);
        setAccId(target.dataset.accountid);
      };
      console.log("account", account);
      return (
        <Card width bold>
          New Transaction
          <select
            value={account}
            onChange={e => handleSelect(e)}
            className="transaction__select"
          >
            <option>Choose acc</option>
            {usersAccounts &&
              usersAccounts.map(acc => (
                <option value={acc.accountNumber} data-accountid={acc.id} key={acc.id}>
                  {acc.accountNumber}
                </option>
              ))}
    

    【讨论】:

    • 谢谢,第一个正在工作!索引一工作正常,遗憾的是我的代码的其他部分有错误:(:D。我很高兴你帮助我解决了至少这个问题!非常感谢!
    猜你喜欢
    • 2020-02-06
    • 2022-11-17
    • 2019-07-18
    • 2023-03-03
    • 2015-10-13
    • 2020-06-07
    • 1970-01-01
    相关资源
    最近更新 更多