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-02-24 15:11:50 +08:00
|
|
|
|
2016-07-10 08:55:43 +08:00
|
|
|
## zh-CN
|
|
|
|
|
2017-01-05 15:47:19 +08:00
|
|
|
自动补全和远程数据结合。
|
2016-02-24 15:11:50 +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';
|
2016-02-24 15:11:50 +08:00
|
|
|
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-02-24 15:11:50 +08:00
|
|
|
});
|
2016-12-19 17:54:25 +08:00
|
|
|
callback(data);
|
|
|
|
}
|
|
|
|
});
|
2016-02-24 15:11:50 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
timeout = setTimeout(fake, 300);
|
|
|
|
}
|
|
|
|
|
2017-02-20 21:54:23 +08:00
|
|
|
class SearchInput extends React.Component {
|
|
|
|
state = {
|
|
|
|
data: [],
|
|
|
|
value: '',
|
|
|
|
}
|
|
|
|
handleChange = (value) => {
|
2016-02-24 19:55:23 +08:00
|
|
|
this.setState({ value });
|
2016-09-27 10:06:34 +08:00
|
|
|
fetch(value, data => this.setState({ data }));
|
2017-02-20 21:54:23 +08:00
|
|
|
}
|
2016-02-24 15:11:50 +08:00
|
|
|
render() {
|
2016-03-04 21:42:38 +08:00
|
|
|
const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
|
2016-02-24 15:11:50 +08:00
|
|
|
return (
|
2017-01-05 15:47:19 +08:00
|
|
|
<Select
|
|
|
|
combobox
|
|
|
|
value={this.state.value}
|
|
|
|
placeholder={this.props.placeholder}
|
|
|
|
notFoundContent=""
|
|
|
|
style={this.props.style}
|
|
|
|
defaultActiveFirstOption={false}
|
|
|
|
showArrow={false}
|
|
|
|
filterOption={false}
|
|
|
|
onChange={this.handleChange}
|
|
|
|
>
|
|
|
|
{options}
|
|
|
|
</Select>
|
2016-02-24 15:11:50 +08:00
|
|
|
);
|
2017-02-20 21:54:23 +08:00
|
|
|
}
|
|
|
|
}
|
2016-02-24 15:11:50 +08:00
|
|
|
|
|
|
|
ReactDOM.render(
|
|
|
|
<SearchInput placeholder="input search text" style={{ width: 200 }} />
|
|
|
|
, mountNode);
|
|
|
|
````
|