我想知道我的选项是否可以在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中为我的代码添加更多值。
不是与反应有关的东西,而是html。 option
元素只能具有有效的属性(例如,值,禁用,标签和选定的属性-如果我没记错的话,在您使用select
元素时使用选定的属性),val2
不是其中之一。
如果可以访问userAccounts
,则将option
值设置为阵列中帐户的index
。然后使用传递的索引调用setAccount
和setAccId
。否则,您可以使用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>
))}