MUI使用本地HTML元素、伪元素、状态和事件的有趣组合来创建TextField
组件.对于TextField
,不存在行为类似于本机HTML Select输入字段的简单size
属性.由于混合使用的元素,如果您想限制菜单选项的高度,则不能使用TextField
SelectProps={{native:true}}
props .梅的MenuItem
需要控制菜单高度.也许最好的解决方案是使用Theme style overrides,如下所示.
Muipopover样式覆盖
样式替代如下所示:
const theme = createTheme( {
components: {
MuiPopover: {
styleOverrides: {
root: {
'&#menu-TEXTFIELD_IDENTIFIER .MuiPaper-root.MuiMenu-paper.MuiPaper-elevation.MuiPaper-rounded.MuiPopover-paper': {
maxHeight: '86px' // Example maximum of two options displayed. About 43px per select option.
}
}
}
}
}
} );
用于显示 Select 菜单选项的组件是MuiPopover.使用样式重写是因为使用带有sx属性的CSS Select 器规则无法轻松 Select 此组件.MuiPopover既不是TextField
所使用的根元素的sibling 元素,也不是其后代.
在上面的样式替代中,TEXTFIELD_IDENTIFIER是您指定给TextField
组件的id
属性的id.TextField
在生成MuiPopover时将前缀menu-分配给id
.使用这id
作为样式覆盖 Select 器的一部分,可以防止覆盖影响应用程序中的每个MuiPopover.
演示
示例代码如下所示.代码为live demo可用.
在演示中,显示了两个 Select 字段,但只有第一个受样式覆盖的影响.虽然这里使用的是ThemeProvider
,但它通常会在应用程序入口点apply.
App.tsx
import * as React from 'react';
import {
Box,
TextField,
MenuItem
} from '@mui/material';
import { createTheme, ThemeProvider } from '@mui/material/styles';
interface selectOption {
value: string
}
const theme = createTheme( {
components: {
MuiPopover: {
styleOverrides: {
root: {
'&#menu-first-select-box .MuiPaper-root.MuiMenu-paper.MuiPaper-elevation.MuiPaper-rounded.MuiPopover-paper': {
maxHeight: '86px' // About 43px per select option.
}
}
}
}
}
} );
export default function ColorTextFields() {
const [ firstValue, setFirstValue ] = React.useState( 'One' );
const [ secondValue, setSecondValue ] = React.useState( 'Six' );
const firstOptions: selectOption[] = [
{ value: 'One' },
{ value: 'Two' },
{ value: 'Three' },
{ value: 'Four' },
{ value: 'Five' }
];
const secondOptions: selectOption[] = [
{ value: 'Six' },
{ value: 'Seven' },
{ value: 'Eight' },
{ value: 'Nine' },
{ value: 'Ten' }
];
function handleFirstChange( e: React.ChangeEvent<HTMLInputElement> ) {
setFirstValue( e.target.value );
}
function handleSecondChange( e: React.ChangeEvent<HTMLInputElement> ) {
setSecondValue( e.target.value );
}
function buildOptions( option: selectOption ): React.ReactElement<typeof MenuItem> {
return (
<MenuItem
key={ option.value }
id={ option.value }
value={ option.value }
>
{ option.value }
</MenuItem>
)
}
return (
<ThemeProvider theme={ theme }>
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '25ch' }
}}
noValidate
autoComplete="off"
>
<TextField
id={ 'first-select-box' }
name={ 'first-select-box' }
label="First Select"
select
SelectProps={ { native: false } }
variant="standard"
value={ firstValue }
onChange={ handleFirstChange }
>
{ firstOptions.map( buildOptions ) }
</TextField>
<TextField
id={ 'second-select-box' }
name={ 'second-select-box' }
label="Second select"
select
SelectProps={ { native: false } }
variant="outlined"
value={ secondValue }
onChange={ handleSecondChange }
>
{ secondOptions.map( buildOptions ) }
</TextField>
</Box>
</ThemeProvider>
);
}