如何使用 JSON 数据填充 React Select? [英] How to populate React Select with JSON data?
本文介绍了如何使用 JSON 数据填充 React Select?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用以下没有 react-select 的 JSON 数据填充选项code>value 和 label
属性?
解决方案
您可以提供 getOptionLabel
和 getOptionValue
道具到 反应选择:
从反应"导入反应;import 从react-select"中选择;常量选项 = [{排序代码:55-77-42-56",帐号:0848890234",accountType: 储蓄账户",帐户名称:XYZ Sam"}//...];导出默认值 () =>{const [value, setValue] = React.useState({});返回 (<选择名称=帐户"选项={选项}价值={价值}onChange={setValue}getOptionLabel={(option) =>option.accountName}getOptionValue={(option) =>option.accountNumber}//它应该是选项中的唯一值.例如.ID/>);};
How to populate options in react-select using the below JSON data which doesn't have value
and label
properties?
[
{
"sortCode": "55-77-42",
"accountNumber": "08488234",
"accountType": "Savings Account",
"accountName": "Mannuel Sam"
},
{
"sortCode": "12-43-98",
"accountNumber": "12365432",
"accountType": "Savings Account",
"accountName": "John Cena"
},
{
"sortCode": "87-20-51",
"accountNumber": "76491234",
"accountType": "Savings Account",
"accountName": "Shweta Pandey"
},
{
"sortCode": "56-73-39",
"accountNumber": "09865479",
"accountType": "Savings Account",
"accountName": "Prerna Singh"
}
]
解决方案
You can provide getOptionLabel
and getOptionValue
props to react-select:
import React from "react";
import Select from "react-select";
const options = [
{
sortCode: "55-77-42-56",
accountNumber: "0848890234",
accountType: "Savings Account",
accountName: "XYZ Sam"
}
// ...
];
export default () => {
const [value, setValue] = React.useState({});
return (
<Select
name="accounts"
options={options}
value={value}
onChange={setValue}
getOptionLabel={(option) => option.accountName}
getOptionValue={(option) => option.accountNumber} // It should be unique value in the options. E.g. ID
/>
);
};
这篇关于如何使用 JSON 数据填充 React Select?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文