[英]How to clear TextField in react?
大家好,我有一個關於單擊圖標后如何清除 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>
)
}}
/>
這是整個解決方案。 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 鏈接 - 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>
)
}}
/>
使用 state 保留文本。 並將該值用作 textare 值。 將 state 更改為 clearSearch function 內部為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.