ash*_*999 2 javascript reactjs material-ui
我正在尝试在 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>
),
}}
/>
)}
/>
Run Code Online (Sandbox Code Playgroud)
我尝试更换...params.InputProps和 的顺序endAdornment,但没有任何改变。
当您检查开发工具中的元素时Autocomplete,您将看到以下内容:input代表搜索区域的 an ,TextField在您的情况下,其结尾装饰是button带有 a 的 a和带有包含透明图标的SearchIcon类的 div 。MuiAutocomplete-endAdornment它们按从左到右的顺序出现在屏幕上。这些都是div具有 CSS 属性的同级:display: inline-flex。这意味着可以使用 重新排序兄弟姐妹order。我们希望按以下顺序从左到右显示元素:输入、清除图标和搜索图标。
如何
我们可以通过覆盖现有样式来实现这一点。由于div容纳这三个元素的 是组件根的子级TextField,因此我们可以将样式应用到 的根类TextField。
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,
},
},
},
});
Run Code Online (Sandbox Code Playgroud)
TextFieldconst 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>
),
}}
/>
)}
/>
Run Code Online (Sandbox Code Playgroud)
选择
正如您所看到的,这需要一些工作。我会考虑使用startAdornment而不是endAdornmentin yourInputProps将搜索图标放置在搜索栏的前面。
| 归档时间: |
|
| 查看次数: |
3504 次 |
| 最近记录: |