点击时移除MUI Autocomplete、TextField占位文本的方法
问题
使用Material-UI(MUI)的Autocomplete组件搭配TextField时,点击搜索栏后占位文本会上移至TextField顶部,希望实现点击后完全移除该占位文本。尝试配置InputLabelProps和InputProps属性后未达到预期效果,现有代码如下:
import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autocomplete'; const top100Cars = [ { label: 'Toyota' }, { label: 'Ford' }, { label: 'Chevrolet' }, { label: 'Tesla' }, { label: 'Honda' }, { label: 'BMW' }, { label: 'Audi' }, { label: 'Mercedes-Benz' }, { label: 'Ferrari' }, { label: 'Porsche' }, { label: 'Lamborghini' }, { label: 'Nissan' }, { label: 'Volkswagen' }, { label: 'Mazda' }, { label: 'DeLorean' }, { label: 'Dodge' }, ]; export default function searchBar() { // const [selectedBrand, setSelectedBrand] = React.useState(null); return ( <Autocomplete disablePortal id="combo-box-demo" options={top100Cars} // value={selectedBrand} // onChange={(event, newValue) => { // setSelectedBrand(newValue); // }} sx={{ width: 254, backgroundColor: 'white', borderRadius: 50, }} renderInput={(params) => ( <TextField {...params} label="Марка" size='small' /> )} /> ); }
解决方案
以下两种方法可以实现点击输入框后隐藏上移的占位文本:
方法1:通过状态控制标签显示
跟踪输入框的聚焦状态,在聚焦或有内容时完全隐藏标签:
import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autocomplete'; const top100Cars = [/* 保持原有数据 */]; export default function searchBar() { const [isFocused, setIsFocused] = React.useState(false); const [selectedBrand, setSelectedBrand] = React.useState(null); return ( <Autocomplete disablePortal id="combo-box-demo" options={top100Cars} value={selectedBrand} onChange={(event, newValue) => { setSelectedBrand(newValue); }} sx={{ width: 254, backgroundColor: 'white', borderRadius: 50, }} renderInput={(params) => ( <TextField {...params} label="Марка" size='small' onFocus={() => setIsFocused(true)} onBlur={() => setIsFocused(false)} InputLabelProps={{ // 禁用默认的浮动收缩效果 shrink: false, sx: { // 当聚焦或有选中值时隐藏标签 display: isFocused || selectedBrand ? 'none' : 'block', }, }} /> )} /> ); }
说明:
- 用
isFocused状态跟踪输入框聚焦状态,selectedBrand跟踪选中值 InputLabelProps.shrink: false禁用标签默认的上移收缩效果- 通过
display样式控制标签仅在未聚焦且无选中值时显示
方法2:直接通过CSS隐藏浮动标签
如果不需要标签的任何浮动效果,直接针对MUI的浮动标签类设置隐藏样式:
import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autocomplete'; const top100Cars = [/* 保持原有数据 */]; export default function searchBar() { return ( <Autocomplete disablePortal id="combo-box-demo" options={top100Cars} sx={{ width: 254, backgroundColor: 'white', borderRadius: 50, }} renderInput={(params) => ( <TextField {...params} label="Марка" size='small' sx={{ // 隐藏处于浮动状态的标签 '& .MuiInputLabel-shrink': { display: 'none', }, }} /> )} /> ); }
说明:
MuiInputLabel-shrink是MUI标签处于浮动(上移)状态时的类名- 通过CSS直接隐藏该类对应的元素,无需额外状态管理
内容的提问来源于stack exchange,提问作者FFFFFFFFF
相关产品推荐
相关产品推荐

