无论我尝试什么,我似乎都无法为 Material-UI Select 组件获得真正的占位符功能。在 <Select />
上使用占位符 Prop 没有用,看起来它要么没有将该 Prop 传递给输入,要么没有以某种方式显示它。
阅读 Select 组件的 Material-UI 演示代码,他们似乎通过使用 <InputLabel />
实现了占位符功能。 .他们有这个厚颜无耻的小动画,将其移动到输入的左上角。不错不错,效果不错。但它不符合我们网站的设计,我想禁用它。不幸的是,disableAnimation
prop 只是使标签跳到左上角,而不是完全消失。
我想要的是让我的下拉组件说“选择项目”作为占位符文本,然后当菜单打开时,该文本应该消失。仅当用户在未选择任何内容的情况下单击下拉菜单时才会返回。如果他们选择了一个值,则该值应替换占位符,并且“选择项目”不应出现在任何地方。
(注意:我在使用 react-select 时工作正常,但我需要使用 Material-UI 的涟漪效果,所以我尝试用 Material UI 覆盖他们的 MenuList 和 MenuItem 组件,但它会将所有 Prop 传递给 DOM 元素和抛出一堆错误。所以我回到绘图板并决定使用整个 Material UI Select 组件。)
当前代码:
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 上,您可以使用
onFocus
跟踪焦点和 onBlur
选择焦点时隐藏标签内容。
关于reactjs - 防止 Material-UI InputLabel 移动到 Select 组件的左上角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57718971/