如何使用 JSON 数据填充 React Select?

IT技术 javascript reactjs react-select
2021-05-02 00:14:45

如何使用以下没有属性的JSON 数据填充react-select 中的选项valuelabel

[       
    {
        "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"
    }
]
1个回答

您可以为react-select提供getOptionLabelgetOptionValueprops

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
      />
  );
};

演示