如何使用OnClick清除自动完成框的数据



我在这里使用了材料UI AutoCompleteBox,它是链接:https://material-ui.com/components/autocomplete/

我的代码是:

<Autocomplete
open={showUniSuggs}
onOpen={this.props.getUniversityOptions}
onChange={(event, value) =>
this.props.handleUniversityChange(value)
}
onClose={this.props.onUniversityClose}
getOptionLabel={(option) => option._id}
options={universityOptions}
loading={uniLoading}
// disabled={disableUniversity}
renderInput={(params) => (
<TextField
{...params}
label="Search for university"
fullWidth
variant="filled"
margin="dense"
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
{uniLoading ? (
<CircularProgress color="inherit" size={20} />
) : null}
{params.InputProps.endAdornment}
</React.Fragment>
),
}}
/>
)}
/>

每当点击自动完成搜索栏调用API并将数据保存在getUniversityOptions上时选择任意值,然后单击自动完成搜索栏的交叉图标,数据已清除。但我希望这些数据将使用点击功能清除。每当点击按钮时,数据都会清除。那么怎么可能做到呢?

您可以用空字符串设置value属性来清除值,如

<Autocomplete value={value} .....
<button onClick={() => { setValue('') }} >Clear Value</button>

这是一个完整的例子:

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {createFilterOptions} from '@material-ui/lab/Autocomplete';
const filter = createFilterOptions();
export default function FreeSoloCreateOption() {
const [value, setValue] = React.useState(null);
return (
<div>
<Autocomplete
value={value}
onChange={(event, newValue) => {
// Create a new value from the user input
if (newValue && newValue.inputValue) {
setValue({
title: newValue.inputValue,
});
return;
}
setValue(newValue);
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
// Suggest the creation of a new value
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
title: `Add "${params.inputValue}"`,
});
}
return filtered;
}}
selectOnFocus
clearOnBlur
id="free-solo-with-text-demo"
options={top100Films}
getOptionLabel={(option) => {
// Value selected with enter, right from the input
if (typeof option === 'string') {
return option;
}
// Add "xxx" option created dynamically
if (option.inputValue) {
return option.inputValue;
}
// Regular option
return option.title;
}}
renderOption={(option) => option.title}
style={{width: 300}}
freeSolo
renderInput={(params) => (
<TextField {...params} label="Free solo with text demo" variant="outlined"/>
)}
/>
<button onClick={() => { setValue('') }} >Clear Value</button>
</div>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{title: 'The Shawshank Redemption', year: 1994},
{title: 'The Godfather', year: 1972},
{title: 'The Godfather: Part II', year: 1974},
{title: 'The Dark Knight', year: 2008},
{title: '12 Angry Men', year: 1957},
];

最新更新