我正在使用React并Material UI制作一個 Web 應用程式。我正在使用Select構建一個多選組件。它作業正常。請參閱下面的代碼。
export const AvailableStations = () => {
const [personName, setPersonName] = React.useState([]);
const handleChangeMultiple = (event) => {
const { options } = event.target;
const value = [];
for (let i = 0, l = options.length; i < l; i = 1) {
if (options[i].selected) {
value.push(options[i].value);
}
}
setPersonName(value);
};
return (
<div>
<Box textAlign='center'>
<FormControl sx={{ m: 0}}>
<InputLabel m={1} shrink htmlFor="select-multiple-native">
Native
</InputLabel>
<Select sx={{minWidth: 170, maxWidth: 170}}
multiple
native
value={personName}
// @ts-ignore Typings are not considering `native`
onChange={handleChangeMultiple}
label="Native"
inputProps={{
id: 'select-multiple-native',
}}
>
{names.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</Select>
</FormControl>
</Box>
</div>
);
}
問題是Select內容與InputLabel. 請參見下圖。

任何人都可以幫助我將它們分開嗎?
uj5u.com熱心網友回復:
您可以通過調整 select 上的 padding-top 并添加一些sx道具來解決此問題:
<Select
sx={{
minWidth: 170,
maxWidth: 170,
pt: 1,
"& .MuiNativeSelect-select": { pt: "8.5px" }
}}
multiple
native
這會將一個 padding-top 間距單位添加到Select. 其中的下一個元素的默認 padding-top 為 16.5px:

在外部元素上添加 8px(一個間距單位)的 padding-top 以避免選項文本與標簽重疊后,默認的 padding-top 需要減少 8px ( 16.5px - 8px = 8.5px) 以避免導致第一個選項上方的空間大于默認值。
這是一個完整的作業示例:
import * as React from "react";
import InputLabel from "@mui/material/InputLabel";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
const names = [
"Oliver Hansen",
"Van Henry",
"April Tucker",
"Ralph Hubbard",
"Omar Alexander",
"Carlos Abbott",
"Miriam Wagner",
"Bradley Wilkerson",
"Virginia Andrews",
"Kelly Snyder"
];
export default function MultipleSelectNative() {
const [personName, setPersonName] = React.useState<string[]>([]);
const handleChangeMultiple = (
event: React.ChangeEvent<HTMLSelectElement>
) => {
const { options } = event.target;
const value: string[] = [];
for (let i = 0, l = options.length; i < l; i = 1) {
if (options[i].selected) {
value.push(options[i].value);
}
}
setPersonName(value);
};
return (
<div>
<FormControl sx={{ m: 1, minWidth: 120, maxWidth: 300 }}>
<InputLabel shrink htmlFor="select-multiple-native">
Native
</InputLabel>
<Select
sx={{
minWidth: 170,
maxWidth: 170,
pt: 1,
"& .MuiNativeSelect-select": { pt: "8.5px" }
}}
multiple
native
value={personName}
// @ts-ignore Typings are not considering `native`
onChange={handleChangeMultiple}
label="Native"
inputProps={{
id: "select-multiple-native"
}}
>
{names.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</Select>
</FormControl>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441239.html
上一篇:延續一對多的關系。如何正確創建?
下一篇:從HTML頁面生成PDF
