如何在 React Typescript 中将自定义类型分配给 Material UI TextField MenuItem 值
How to Assign Custom Types to Material UI TextField MenuItem Values in React Typescript
我的代码中存在类型冲突,我不确定简单的转换是否可以解决我的问题,或者我的代码是否存在根本性错误。
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 中工作的相同代码
这是我在 TS 中的代码(不工作)codesandbox
不要使用整个存储对象作为值,只需使用 store.storeId
。您还需要将文本字段的值属性更改为 selectedStore.storeId
.
我的代码中存在类型冲突,我不确定简单的转换是否可以解决我的问题,或者我的代码是否存在根本性错误。
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 中工作的相同代码这是我在 TS 中的代码(不工作)codesandbox
不要使用整个存储对象作为值,只需使用 store.storeId
。您还需要将文本字段的值属性更改为 selectedStore.storeId
.