Material UI Autocomplete上的打字稿平等问题

问题描述 投票:1回答:1

数据存储为:

 { iso: "gb", label: "United Kingdom", country: "United Kingdom" },
 { iso: "fr", label: "France", country: "France" }

传递给自动完成的值是:

{ iso: "gb", label: "United Kingdom", country: "United Kingdom" }

控制台中报告错误

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

value={}上报类型错误

类型'字符串|无法将“ ICountry”分配给“ 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;

countries.ts


import { ICountry } from "./investor";

export const countries: ICountry[] = [
  {
    iso: "gb",
    label: "United Kingdom",
    country: "United Kingdom"
  },
  {
    iso: "fr",
    label: "France",
    country: "France"
  }
];
reactjs typescript material-ui formik
1个回答
0
投票

Material-UI的完整消息是:

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

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

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

getOptionSelected={(option, value) => option.iso === value.iso}

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

可以通过value={values.address.country as ICountry}解决类型错误。

以下是您的沙盒的有效版本:https://codesandbox.io/s/autocomplete-getoptionselected-b6n3s

© www.soinside.com 2019 - 2024. All rights reserved.