Material UI新手求助:如何为TextField添加鼠标悬停边框?
解决Material UI TextField鼠标悬停显示边框的问题
注意:你当前提供的代码里没有引入TextField组件,以下是两种实现鼠标悬停时显示边框的可行方案:
方案一:用styled自定义TextField组件
通过styled方法封装TextField,直接在样式中定义hover状态的边框样式:
import React from 'react'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; import TextField from '@mui/material/TextField'; import { styled } from '@mui/material/styles'; const StyledTextField = styled(TextField)(({ theme }) => ({ '&:hover .MuiOutlinedInput-root': { '&:not(.Mui-focused) .MuiOutlinedInput-notchedOutline': { borderColor: '#2196f3', // 替换成你需要的边框颜色 borderWidth: '2px', // 可选:调整边框宽度 } } })); const Shipping = () => { return ( <Box> <Typography variant="h5">Shipping Information</Typography> <Box sx={{ marginTop: '60px', padding: 2 }}> <StyledTextField label="Name" defaultValue="Caeleb Dressel" fullWidth margin="normal" /> <StyledTextField label="Phone" defaultValue="+14097575013" fullWidth margin="normal" /> <StyledTextField label="Email" defaultValue="caelebdressel@example.com" fullWidth margin="normal" /> <StyledTextField label="Address" defaultValue="417 Wahignton Ave. Green cove Springg, Plorida 39495" fullWidth margin="normal" /> </Box> </Box> ); }; export default Shipping;
方案二:直接用sx属性设置样式
如果不想单独封装组件,可以直接在TextField的sx属性中定义hover样式:
import React from 'react'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; import TextField from '@mui/material/TextField'; const Shipping = () => { return ( <Box> <Typography variant="h5">Shipping Information</Typography> <Box sx={{ marginTop: '60px', padding: 2 }}> <TextField label="Name" defaultValue="Caeleb Dressel" fullWidth margin="normal" sx={{ '&:hover .MuiOutlinedInput-root:not(.Mui-focused) .MuiOutlinedInput-notchedOutline': { borderColor: '#2196f3', borderWidth: '2px' } }} /> {/* 其余TextField可复用相同的sx样式 */} <TextField label="Phone" defaultValue="+14097575013" fullWidth margin="normal" sx={{ '&:hover .MuiOutlinedInput-root:not(.Mui-focused) .MuiOutlinedInput-notchedOutline': { borderColor: '#2196f3', borderWidth: '2px' } }} /> </Box> </Box> ); }; export default Shipping;
核心说明
- Material UI的Outlined类型TextField,边框对应的DOM元素类名是
.MuiOutlinedInput-notchedOutline,需要通过层级选择器定位到hover状态下的该元素 - 加上
:not(.Mui-focused)是为了避免hover样式覆盖组件聚焦时的默认样式,若希望聚焦时也保留hover边框效果,可移除这个条件
内容的提问来源于stack exchange,提问作者Muhammad Mehedi Hasan
相关产品推荐
相关产品推荐

