【问题标题】:How to clear TextField in react?如何在反应中清除 TextField?
【发布时间】:2021-12-29 03:44:24
【问题描述】:

大家好,我有一个关于单击图标后如何清除 TextField 的问题?谢谢

const [filteredLocations, setFilteredLocations] = useState(locations);

const clearSearch = () => {
    // i dont know what should i put here TextField.clear() or so what ever
  };
  const filterResults = (e) => {
    ....
    setFilteredLocations(filteredLocations);
  };

    <TextField
      placeholder="Search Locations"
      onChange={filterResults}
      InputProps={{
        endAdornment: (
          <IconButton onClick={clearSearch} edge="end">
            <ClearIcon />
          </IconButton>
        )
      }}
    />

【问题讨论】:

标签: javascript reactjs material-ui


【解决方案1】:

这是整个解决方案。 filterResults 函数出现错误。

import {useState} from 'react'
import TextField from "@mui/material/TextField";
import IconButton from "@mui/material/IconButton";
import ClearIcon from '@mui/icons-material/ClearOutlined'

export default function App() {
  const [filteredLocations, setFilteredLocations] = useState('');

const clearSearch = () => {
    setFilteredLocations('')
  };
  const filterResults = (e) => {
    setFilteredLocations(e.target.value);
  };

    
  return (
    <div className="App">
      <TextField
      placeholder="Search Locations"
      value={filteredLocations}
      onChange={filterResults}
      InputProps={{
        endAdornment: (
          <IconButton onClick={clearSearch} edge="end">
            <ClearIcon />
          </IconButton>
        )
      }}
    />
    </div>
  );
}

Codesnadbox 链接 - https://codesandbox.io/s/how-to-clear-textfield-in-react-tb73t

【讨论】:

  • 它不起作用@moshfiqrony,当我单击文本字段时出现错误The above error occurred in the &lt;e&gt; component:
  • 您的 filterResults 函数出现错误。再次检查解决方案。我还添加了工作代码框链接
  • 无法在 Codesnadbox 中输入
  • 你确定吗?因为我可以在那里写作。也可以隐身
【解决方案2】:
const [filteredLocations, setFilteredLocations] = useState(locations);

const clearSearch = () => {
  setFilteredLocations("");
  };
  const filterResults = (e) => {
    ....
    setFilteredLocations(filteredLocations);
  };

    <TextField
      value = {filteredLocations}
      placeholder="Search Locations"
      onChange={filterResults}
      InputProps={{
        endAdornment: (
          <IconButton onClick={clearSearch} edge="end">
            <ClearIcon />
          </IconButton>
        )
      }}
    />

用户状态以保留文本。并将该值用作 textare 值。在 clearSearch 函数中将该状态更改为空。

【讨论】:

  • 它不起作用@Kasun,当我单击文本字段时出现错误The above error occurred in the &lt;e&gt; component:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 2022-06-12
  • 2022-08-09
  • 1970-01-01
  • 2020-04-21
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多