[英]React Material UI - Autocomplete Component button after clear field button
我正在尝试在 Material UI 上添加我的Autocomplete
组件的搜索按钮。 到目前为止,我已经能够添加按钮,但是它总是出现在清除按钮之前,如下所示:
如何设置InputProps
以使按钮出现在X
之后。
到目前为止,我有:
<Autocomplete
id="search-input"
freeSolo
renderInput={(params) => (
<TextField
{...params}
placeholder={`...`}
margin="normal"
variant="outlined"
size="medium"
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
<IconButton size="small">
<SearchIcon />
</IconButton>
{params.InputProps.endAdornment}
</React.Fragment>
),
}}
/>
)}
/>
我尝试替换...params.InputProps
和endAdornment
的顺序,但没有任何变化。
当您在开发工具中检查Autocomplete
中的元素时,您将看到以下内容:代表搜索区域的input
, TextField
的结尾装饰,在您的情况下是一个带有SearchIcon
的button
和一个带有 class MuiAutocomplete-endAdornment
的 div MuiAutocomplete-endAdornment
包含清除图标。 它们以从左到右的顺序出现在屏幕上。 这些都是具有 CSS 属性的div
中的兄弟姐妹: display: inline-flex
。 这意味着可以使用order
重新排序兄弟姐妹。 我们希望从左到右按以下顺序显示元素:输入、清除图标和搜索图标。
如何
我们可以通过覆盖现有的 styles 来实现这一点。 由于包含这三个元素的div
是TextField
组件根的子元素,因此我们可以将样式应用于TextField
的根 class 。
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
textFieldRoot: {
"& > div.MuiAutocomplete-inputRoot[class*='MuiOutlinedInput-root']": {
// default paddingRight was 39px since clear icon was positioned absolute
paddingRight: "9px",
// Search icon
"& button": {
order: 3, // order 3 means the search icon will appear after the clear icon which has an order of 2
},
// Clear icon
"& > div.MuiAutocomplete-endAdornment": {
position: "relative", // default was absolute. we make it relative so that it is now within the flow of the other two elements
order: 2,
},
},
},
});
TextField
的根const classes = useStyles();
<Autocomplete
id="search-input"
freeSolo
options={[]}
renderInput={(params) => (
<TextField
{...params}
classes={{
root: classes.textFieldRoot, // apply class here
}}
placeholder={`...`}
margin="normal"
variant="outlined"
size="medium"
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
<IconButton size="small">
<SearchIcon />
</IconButton>
{params.InputProps.endAdornment}
</React.Fragment>
),
}}
/>
)}
/>
选择
如您所见,这是一项工作。 我会考虑在InputProps
中使用startAdornment
而不是endAdornment
将搜索图标放在搜索栏的前面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.