我正在使用MUI InputBase制作自定义输入组件,并且我希望有一个“清除”按钮endAdornment,仅在将鼠标悬停在输入上方时才会显示:
<InputBase
inputComponent={getCustomInputComponent()}
onClick={onClick}
...
endAdornment={
<IconButton
size='small'
onClick={handleClear}>
<IconClear fontSize='small'/>
</IconButton>
}
/>
类似于其新的“自动完成”组件的工作方式:https://material-ui.com/components/autocomplete/
我已经看过Autocomplete的源代码,但是我无法在我的组件中使用它,有什么建议吗?
答案 0 :(得分:0)
下面是一个示例,该示例与“自动完成”中的操作大致等效。该方法的要点是默认情况下将图标隐藏,然后在悬停输入(visible
)和输入集中(&:hover $clearIndicatorDirty
)时将可见性翻转到& .Mui-focused
,但仅当输入中当前有文字时才使用(clearIndicatorDirty
仅在value.length > 0
时适用)。
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import IconButton from "@material-ui/core/IconButton";
import ClearIcon from "@material-ui/icons/Clear";
import clsx from "clsx";
const useStyles = makeStyles(theme => ({
root: {
"&:hover $clearIndicatorDirty, & .Mui-focused $clearIndicatorDirty": {
visibility: "visible"
}
},
clearIndicatorDirty: {},
clearIndicator: {
visibility: "hidden"
}
}));
export default function CustomizedInputBase() {
const classes = useStyles();
const [value, setValue] = React.useState("");
return (
<TextField
variant="outlined"
className={classes.root}
value={value}
onChange={e => setValue(e.target.value)}
InputProps={{
endAdornment: (
<IconButton
className={clsx(classes.clearIndicator, {
[classes.clearIndicatorDirty]: value.length > 0
})}
size="small"
onClick={() => {
setValue("");
}}
>
<ClearIcon fontSize="small" />
</IconButton>
)
}}
/>
);
}
相关文档: