ant-design/components/select/demo/search-box.md

90 lines
1.8 KiB
Markdown
Raw Normal View History

2016-03-31 09:40:55 +08:00
---
order: 9
2016-10-06 18:54:28 +08:00
title:
2016-07-10 08:55:43 +08:00
zh-CN: 搜索框
en-US: Search Box
2016-03-31 09:40:55 +08:00
---
2016-07-10 08:55:43 +08:00
## zh-CN
2017-01-05 15:47:19 +08:00
自动补全和远程数据结合。
2016-07-10 08:55:43 +08:00
## en-US
2017-01-05 15:47:19 +08:00
Autocomplete with remote ajax data.
2016-07-10 08:55:43 +08:00
2017-02-13 10:55:53 +08:00
````jsx
2017-01-05 15:47:19 +08:00
import { Select } from 'antd';
2016-12-19 17:54:25 +08:00
import jsonp from 'fetch-jsonp';
import querystring from 'querystring';
const Option = Select.Option;
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,
});
2016-12-19 17:54:25 +08:00
jsonp(`https://suggest.taobao.com/sug?${str}`)
.then(response => response.json())
.then((d) => {
if (currentValue === value) {
const result = d.result;
const data = [];
result.forEach((r) => {
data.push({
value: r[0],
text: r[0],
});
});
2016-12-19 17:54:25 +08:00
callback(data);
}
});
}
timeout = setTimeout(fake, 300);
}
class SearchInput extends React.Component {
state = {
data: [],
value: '',
}
handleChange = (value) => {
2016-02-24 19:55:23 +08:00
this.setState({ value });
fetch(value, data => this.setState({ data }));
}
render() {
2016-03-04 21:42:38 +08:00
const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
return (
2017-01-05 15:47:19 +08:00
<Select
mode="combobox"
2017-01-05 15:47:19 +08:00
value={this.state.value}
placeholder={this.props.placeholder}
notFoundContent=""
style={this.props.style}
defaultActiveFirstOption={false}
showArrow={false}
filterOption={false}
onChange={this.handleChange}
>
{options}
</Select>
);
}
}
ReactDOM.render(
<SearchInput placeholder="input search text" style={{ width: 200 }} />
, mountNode);
````