可以 具有多个值吗?使用React-hooks

问题描述 投票:0回答:2

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

有人可以帮我如何为我的选择增加新的价值吗?如您所见,“ 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
2个回答
0
投票

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


0
投票

如果可以访问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>
          ))}
© www.soinside.com 2019 - 2024. All rights reserved.