Material UI Autocomplete 上的 Typescript Equality 问题

Xav*_*ram 14 typescript reactjs material-ui formik

数据存储为:

 { iso: "gb", label: "United Kingdom", country: "United Kingdom" },
 { iso: "fr", label: "France", country: "France" }
Run Code Online (Sandbox Code Playgroud)

传递给自动完成的值是:

{ iso: "gb", label: "United Kingdom", country: "United Kingdom" }
Run Code Online (Sandbox Code Playgroud)

控制台报错

Material-UI:提供给自动完成的值无效。没有一个选项与{"label":"United Kingdom","iso":"gb","country":"United Kingdom"}.

报告的类型错误 value={}

输入'字符串| ICountry' 不可分配给类型 'ICountry | ICountry[] | 空| 不明确的'。类型 'string' 不能分配给类型 'ICountry | ICountry[] | 空| 不明确的'。

问题:将数据传递给组件并未将其设置为相应的选项,我对如何解决此问题一无所知。

问题代码沙盒:https ://codesandbox.io/s/charming-firefly-zl3qd?file =/ src/App.tsx

import * as React from "react";
import { Box, Typography, TextField, Button } from "@material-ui/core";
import { Autocomplete } from "@material-ui/lab";
import "./styles.css";
import { countries } from "./countries";
import { investors } from "./investor";
import { Formik } from "formik";

interface ICountry {
  iso: string;
  country: string;
  label: string;
}

const isoToFlag = (isoCode: string) => {
  if (isoCode) {
    return typeof String.fromCodePoint !== "undefined"
      ? isoCode
          .toUpperCase()
          .replace(/./g, char =>
            String.fromCodePoint(char.charCodeAt(0) + 127397)
          )
      : isoCode;
  }
  return "";
};

const App: React.FC = () => {
  const investor = investors.find(element => element.id === "123");


  return (
    <div className="App">
      <Formik
        initialValues={{
          address: {
            country: investor?.legal.address.country ? investor.legal.address.country : '',
          }
        }}
        onSubmit={(values, actions) => {
          console.log({ values, actions });
          actions.setSubmitting(false);
        }}
      >
        {({ submitForm, isSubmitting, values, setFieldValue, setValues }) => {

          return (
            <form>

              <Autocomplete
                id="country"
                options={countries}
                getOptionLabel={option => option.label}
                value={values.address.country}
                renderOption={(option: ICountry) => (
                  <Box display="flex" flexDirection="row" alignItems="center">
                    <Box mr={1}>{isoToFlag(option.iso)}</Box>
                    <Box>
                      <Typography variant="body2">{option.label}</Typography>
                    </Box>
                  </Box>
                )}
                onChange={(e: object, value: any | null) => {
                  console.log('do the types match?', typeof value === typeof values.address.country);
                  console.log('do the objects match?', value === values.address.country);
                  console.log('the objects in question', value, values.address.country);
                  console.log("                  ");
                  setFieldValue("address.country", value);
                }}
                renderInput={params => (
                  <TextField
                    {...params}
                    name="address.country"
                    label="Country"
                    variant="outlined"
                    fullWidth
                  />
                )}
              />
              <Button
                variant="contained"
                size="large"
                color="primary"
                disabled={isSubmitting}
                onClick={submitForm}
              >
                Submit
              </Button>
            </form>
          );
        }}
      </Formik>
    </div>
  );
};

export default App;
Run Code Online (Sandbox Code Playgroud)

国家.ts


import { ICountry } from "./investor";

export const countries: ICountry[] = [
  {
    iso: "gb",
    label: "United Kingdom",
    country: "United Kingdom"
  },
  {
    iso: "fr",
    label: "France",
    country: "France"
  }
];
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 35

来自的完整信息Material-UI是:

Material-UI:提供给自动完成的值无效。没有一个选项与{"label":"United Kingdom","iso":"gb","country":"United Kingdom"}. 您可以使用getOptionSelectedprop 来自定义相等性测试。

默认的相等性测试很简单===,因此如果您的选项是对象,则您的值必须是这些确切对象之一才能匹配。具有相同值的不同对象将不匹配。

但是正如消息告诉您的那样,您可以通过getOptionSelectedprop自定义相等性测试。例如,您可以指定:

getOptionSelected={(option, value) => option.iso === value.iso}
Run Code Online (Sandbox Code Playgroud)

或者您可以对所有对象属性进行深度相等性检查。

类型错误可以用value={values.address.country as ICountry}.

这是您的沙箱的工作版本:https : //codesandbox.io/s/autocomplete-getoptionselected-b6n3s