[英]How to clear TextField after ENTER key press in React
I am using Mui component TextField in TypeSCript and I want to clear TextField after ENTER key is pressed.我在 TypeSCript 中使用 Mui 组件 TextField,我想在按下 ENTER 键后清除 TextField。
Here is my code snippet这是我的代码片段
<TextField
{...params}
autoFocus
className="SymbolInput"
onChange={(e) => {
setSearchTerm(e.target.value);
handleInputdebounced(e.target.value);
}}
onBlur={clearState}
onFocus={() => setSearchResults([])}
placeholder="Add symbols"
name="searchname"
onKeyPress={(e) => {
if (e.key === 'Enter') {
onPressEnter();
setSearchTerm('');
}
}}
InputProps={{
...params.InputProps,
type: 'search',
sx: { pb: '2px', pt: '2px' },
endAdornment: (
<InputAdornment position="end" sx={{width:0}}>
{loading ? <CircularProgress color="inherit" size={20} /> : <SearchIcon />}
</InputAdornment>
),
}}
inputProps={{
...params.inputProps,
sx: { textTransform: 'uppercase', },
}}
/>
const onPressEnter = async () => {
if (searchTerm && searchTerm.length > 0) {
onAddSymbol(searchTerm);
}
};
const handleSearchChange = async (searchTerm: string) => {
const searchValue = searchTerm;
//Check if there are any previous pending requests
if (typeof autoCompleteCancelToken != typeof undefined) {
autoCompleteCancelToken?.cancel('Operation canceled due to new request.');
}
//Save the cancel token for the current request
autoCompleteCancelToken = axios.CancelToken.source();
if (searchValue && searchValue.length > 0) {
setLoading(true);
setSearchTerm(searchTerm);
const response = await companyLookup(searchTerm, { cancelToken: autoCompleteCancelToken?.token });
if (!response.hasErrors) {
setSearchResults(response.data || []);
}
setGetValue(searchValue);
setEditable(false);
setLoading(false);
}
if (searchValue.length == 0) {
setSearchResults([]);
}
};
const handleInputdebounced = useMemo(() => debounce(handleSearchChange, 200), []);
<TextField
{...params}
value={searchTerm}
autoFocus
className="SymbolInput"
onChange={(e) => {
setSearchTerm(e.target.value);
handleInputdebounced(e.target.value);
}}
onBlur={clearState}
onFocus={() => setSearchResults([])}
placeholder="Add symbols"
name="searchname"
onKeyPress={(e) => {
if (e.key === 'Enter') {
onPressEnter();
setSearchTerm('');
}
}}
InputProps={{
...params.InputProps,
type: 'search',
sx: { pb: '2px', pt: '2px' },
endAdornment: (
<InputAdornment position="end" sx={{width:0}}>
{loading ? <CircularProgress color="inherit" size={20} /> : <SearchIcon />}
</InputAdornment>
),
}}
inputProps={{
...params.inputProps,
sx: { textTransform: 'uppercase', },
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.