简体   繁体   English

如何在反应中清除 TextField?

[英]How to clear TextField in react?

Hi everyone i have a question regarding on how to clear TextField after clicking the icon?大家好,我有一个关于单击图标后如何清除 TextField 的问题? thanks谢谢

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>
        )
      }}
    />

Here is the whole solve.这是整个解决方案。 There was an error in the filterResults function. filterResults function 出现错误。

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 link - https://codesandbox.io/s/how-to-clear-textfield-in-react-tb73t Codesnadbox 链接 - https://codesandbox.io/s/how-to-clear-textfield-in-react-tb73t

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>
        )
      }}
    />

User a state to keep the text.使用 state 保留文本。 And use that value as textare value.并将该值用作 textare 值。 Change that state to empty inside clearSearch function.将 state 更改为 clearSearch function 内部为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM