防止材料 UI 输入标签移动到选择组件的左上角



无论我尝试什么,我似乎都无法获得Material-UI Select组件的真正占位符功能。在<Select />上使用占位符道具不起作用,看起来它要么没有将该道具传递给输入,要么没有以某种方式显示它。

通读 Select 组件的 Material-UI 演示代码,似乎他们通过使用<InputLabel />实现了占位符功能。他们有这个厚颜无耻的小动画,可以将其移动到输入的左上角。好吧,很酷,这是一个很好的效果。但它不符合我们网站的设计,我想禁用它。不幸的是,disableAnimation道具只是导致标签跳到左上角,而不是完全消失。

我想要的是让我的下拉组件将"选择项目"作为占位符文本,然后当菜单打开时,该文本应该消失。仅当用户单击下拉列表而不选择任何内容时,它才会返回。如果他们选择一个值,则该值应替换占位符,并且"选择项目"不应出现在任何位置。

(注意:使用 react-select 时,我工作正常,但我需要使用 Material-UI 的涟漪效果,所以我尝试用 Material UI 覆盖它们的 MenuList 和 MenuItem 组件,但它将所有道具传递给 DOM 元素并抛出一堆错误。所以我回到绘图板,决定使用整个材质UI选择组件。

当前代码:

const Dropdown = ({options, ...props}) => {
const [selected, setSelected] = useState('');
const testOptions = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
const handleChange = (selected) => {
setSelected(selected);
console.log('is anything happening')
}
options = options || testOptions;
const menuItems = options.map((option, index) => (
<StyledMenuItem
key={index}
value={option.value}
label={option.label}
/>
));
return (
<FormControl hiddenLabel>
<InputLabel disableAnimation>Select Item</InputLabel>
<StyledSelect
value={selected}
onChange={handleChange}
variant="outlined"
disableUnderline={true}
>
<MenuItem value="">
<em>Select Item</em>
</MenuItem>
{menuItems}
</StyledSelect>
</FormControl>
)
};

const StyledMenuItem = styled(MenuItem)`
min-height: 32px;
height: 32px;
padding: 0 12px;
font-family: 'Work Sans', sans-serif;
font-weight: 400;
font-size: 17px;
line-height: 20px;
color: ${colors.primary800};
outline: none;
&:hover {
background-color: ${colors.primary100};
}
& .MuiTouchRipple-root {
color: ${colors.primary050};
}
`
const StyledSelect = styled(Select)`
input::-webkit-contacts-auto-fill-button,
input::-webkit-credentials-auto-fill-button {
display: none !important;
}
border: 1px solid ${colors.primary400};
border-radius: 2px;
height: 40px;
box-shadow: none;
outline: none;
& .MuiSelect-icon {
fill: ${colors.primary300};
width: 36px;
height: 36px;
top: inherit;
}
`

我找不到一种真正干净的方法,但以下内容似乎可以解决问题:

<InputLabel shrink={false}>
{selected !== '' && 'Select item'}
</InputLabel>

添加shrink={false}可确保标签在聚焦时不会向上移动。使用默认的 Material-UI 样式时,选项将位于 InputLabel 上方,因此在选择时不会看到它。然后,当选择一个值时,将设置selected变量,并且文本将从标签中隐藏。

如果由于自定义样式的原因,所选项目未显示在 InputLabel 上,则可以使用onFocusonBlur跟踪焦点,以便在选择焦点时隐藏标签内容。

使用 select 属性将 MenuItem 组件包装在 TextField 组件内,而不是包装 Select 组件将完成这项工作。希望这有帮助。

<TextField select name="categoryName" fullWidth label="Select Category">
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</TextField>

最新更新