mirror of
https://gitee.com/ant-design/ant-design.git
synced 2024-12-15 17:31:25 +08:00
92 lines
1.8 KiB
Markdown
92 lines
1.8 KiB
Markdown
---
|
|
order: 9
|
|
title:
|
|
zh-CN: 搜索框
|
|
en-US: Search Box
|
|
---
|
|
|
|
## zh-CN
|
|
|
|
自动补全和远程数据结合。
|
|
|
|
## en-US
|
|
|
|
Autocomplete with remote ajax data.
|
|
|
|
````jsx
|
|
import { Select } from 'antd';
|
|
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,
|
|
});
|
|
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],
|
|
});
|
|
});
|
|
callback(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
timeout = setTimeout(fake, 300);
|
|
}
|
|
|
|
const SearchInput = React.createClass({
|
|
getInitialState() {
|
|
return {
|
|
data: [],
|
|
value: '',
|
|
};
|
|
},
|
|
handleChange(value) {
|
|
this.setState({ value });
|
|
fetch(value, data => this.setState({ data }));
|
|
},
|
|
render() {
|
|
const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
|
|
return (
|
|
<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>
|
|
);
|
|
},
|
|
});
|
|
|
|
ReactDOM.render(
|
|
<SearchInput placeholder="input search text" style={{ width: 200 }} />
|
|
, mountNode);
|
|
````
|