【问题标题】:How to Assign Custom Types to Material UI TextField MenuItem Values in React Typescript如何在 React Typescript 中为 Material UI TextField MenuItem 值分配自定义类型
【发布时间】:2021-12-28 20:43:02
【问题描述】:

我的代码中存在类型冲突,我不确定简单的转换是否可以解决我的问题,或者我的代码是否存在根本性错误。

import React from "react";
import TextField from "@mui/material/TextField";
import MenuItem from "@mui/material/MenuItem";

interface Store {
  storeId: string;
  storeName: string;
}

const mockApi: Store[] = [
  {
    storeId: "1",
    storeName: "Store 1"
  },
  {
    storeId: "2",
    storeName: "Store 2"
  },
  {
    storeId: "3",
    storeName: "Store 3"
  }
];

export default function App() {
  const [selectedStore, setSelectedStore] = React.useState<Store>();
  const [stores, setStores] = React.useState<Store[]>([]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedStore(event.target.value); // Type conflict here string not a Store
  };

  React.useEffect(() => {
    setStores(mockApi);
    setSelectedStore(mockApi[1]);
  }, []);

  return (
    <div className="App">
      <TextField
        id="outlined-select-currency"
        select
        label="Store"
        value={selectedStore}
        onChange={handleChange}
        size="small"
        style={{ width: 200 }}
        fullWidth
      >
        {stores &&
          stores.map((store) => (
            <MenuItem key={store.storeId} value={store}> // type conflict here Store is not a string
              {store.storeName}
            </MenuItem>
          ))}
      </TextField>
      {selectedStore && <div>Store name: {selectedStore.storeName}</div>}
    </div>
  );
}

我在codesandbox 中得到了在 JS 中工作的相同代码

这是我在codesandbox TS 中的代码(不工作)

【问题讨论】:

    标签: reactjs material-ui menuitem react-typescript


    【解决方案1】:

    不要使用整个 store 对象作为值,而是使用 store.storeId。您还需要将文本字段的 value 属性更改为 selectedStore.storeId

    见:https://codesandbox.io/s/silent-fire-irpjz

    【讨论】:

    • 我喜欢这个解决方案,但是当我这样做时,它会让我回到上一个问题,在页面加载时设置的初始值不会显示在 TextField 中,直到它再次被选中。
    • @SamuelZrna 在你的 useEffect 中尝试在 setStores 之前调用 setSelectedStore
    • 好的,我看到了问题。这是因为最初没有 selectedStore,所以 React 将 TextField 呈现为不受控制的,但随后您添加了 selectedStore,因此您更改为受控组件,而 React 不喜欢这种更改。如果不存在 selectedStore,您可以通过将空对象传递给文本字段的值来解决此问题。我已经用代码 sn-p 的工作版本更新了我的答案
    猜你喜欢
    • 2019-08-30
    • 2019-12-27
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2020-06-29
    • 2020-07-30
    相关资源
    最近更新 更多