[英]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.