Material UI TextField type='search':如何替换/修改'clear'图标?

问题描述 投票:0回答:3

在下面的示例中,我使用 type='search' 的文本字段。 enter image description here

“清除”图标自动出现。如何更改此图标的样式或将其替换为我自己的图标?

import SearchIcon from '@material-ui/icons/Search';
    
<TextField
   placeholder="Search"
   type="search"
   variant="outlined"
   fullWidth
   size="small"
   onChange={handleSearchFieldOnChange}
   InputProps={{
       startAdornment: (
           <InputAdornment position="start">
              <SearchIcon />
           </InputAdornment>
            ),
         }}
 />
reactjs material-ui
3个回答
26
投票

你可以这样做:

import InputAdornment from "@material-ui/core/InputAdornment";
import TextField from "@material-ui/core/TextField";
import SearchIcon from "@material-ui/icons/Search";
import { IconButton } from "@material-ui/core";
import CancelRoundedIcon from '@material-ui/icons/CancelRounded'
export default function InputWithIcon() {
  const [value, setValue] = useState("");

  return (
    <TextField
      placeholder="Search"
      type="text"
      variant="outlined"
      fullWidth
      size="small"
      onChange={(e) => setValue(e.target.value)}
      value={value}
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <SearchIcon />
          </InputAdornment>
        ),

        endAdornment: value && (
          <IconButton
            aria-label="toggle password visibility"
            onClick={() => setValue("")}
          ><CancelRoundedIcon/></IconButton>
        )
      }}
    />
  );
}

参见沙盒


2
投票

我们可以使用IconButton来放置清除事件。每当我们有值时,清除图标就会可见,否则它将被禁用

示例:

   <TextField
      placeholder="Search"
      type="text"
      variant="outlined"
      fullWidth
      size="small"
      onChange={(e) => setValue(e.target.value)}
      value={value}
      InputProps={{
        endAdornment: (
          <IconButton onClick={() => setValue("")}>
           {value.length > 0 ? <ClearOutlinedIcon/> : ''}
          </IconButton>
        )
      }}
    />

0
投票

对于使用 MUI 6+ 的任何人,

InputProps
设置为
deprecated
,并且应将其替换为
slotProps
,并将
input
属性分配给具有
startAdornment
endAdornment
作为属性的对象。

要解决此问题,请替换以下代码片段:

InputProps={{
  startAdornment: (
    <InputAdornment position="start">
      <SearchIcon />
    </InputAdornment>
  ),

  endAdornment: value && (
    <IconButton
      aria-label="toggle password visibility"
      onClick={() => setValue("")}
    ><CancelRoundedIcon/></IconButton>
  )
}}

具有以下内容:

slotProps={{
  input: {
    startAdornment: (
      <InputAdornment position="start">
        <SearchIcon />
      </InputAdornment>
    ),
    endAdornment: value && (
      <IconButton
        aria-label="toggle password visibility"
        onClick={() => setValue("")}
      ><CancelRoundedIcon/></IconButton>
    )
  },
}}

欲了解更多信息,请参阅本指南

© www.soinside.com 2019 - 2024. All rights reserved.