mirror of
https://github.com/zhigang1992/form-render.git
synced 2026-06-11 16:09:45 +08:00
84 lines
1.7 KiB
JavaScript
84 lines
1.7 KiB
JavaScript
import { Select } from 'antd';
|
|
import jsonp from 'fetch-jsonp';
|
|
import querystring from 'querystring';
|
|
const { Option } = Select;
|
|
|
|
let timeout;
|
|
let currentValue;
|
|
|
|
function fetch(value, callback) {
|
|
if (timeout) {
|
|
clearTimeout(timeout);
|
|
timeout = null;
|
|
}
|
|
currentValue = value;
|
|
|
|
function fake() {
|
|
const str = querystring.encode({
|
|
code: 'utf-8',
|
|
q: value,
|
|
});
|
|
jsonp(`https://suggest.taobao.com/sug?${str}`)
|
|
.then(response => response.json())
|
|
.then(d => {
|
|
if (currentValue === value) {
|
|
const { result } = d;
|
|
const data = [];
|
|
result.forEach(r => {
|
|
data.push({
|
|
value: r[0],
|
|
text: r[0],
|
|
});
|
|
});
|
|
callback(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
timeout = setTimeout(fake, 300);
|
|
}
|
|
|
|
class SearchInput extends React.Component {
|
|
state = {
|
|
data: [],
|
|
};
|
|
|
|
handleSearch = value => {
|
|
if (value) {
|
|
fetch(value, data => this.setState({ data }));
|
|
} else {
|
|
this.setState({ data: [] });
|
|
}
|
|
};
|
|
|
|
handleChange = value => {
|
|
const { onChange, name } = this.props;
|
|
onChange(name, value);
|
|
};
|
|
|
|
render() {
|
|
const { value, options: uiOptions } = this.props;
|
|
const options = this.state.data.map(d => (
|
|
<Option key={d.value}>{d.text}</Option>
|
|
));
|
|
return (
|
|
<Select
|
|
{...uiOptions}
|
|
style={{ width: '100%' }}
|
|
showSearch
|
|
value={value || undefined}
|
|
defaultActiveFirstOption={false}
|
|
showArrow={false}
|
|
filterOption={false}
|
|
onSearch={this.handleSearch}
|
|
onChange={this.handleChange}
|
|
notFoundContent={null}
|
|
>
|
|
{options}
|
|
</Select>
|
|
);
|
|
}
|
|
}
|
|
|
|
export default SearchInput;
|