How to create auto complete textbox using reactJs in .net framework.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
var InputAutoComplete=React.createClass({
getInitialState: function () {
return {
input: '',
selected: false
}
},
handleChange : function(event) {
this.setState({
input: event.target.value,
selected: true
});
},
liHandleClick: function(event) {
this.setState({
input: event.target.innerText,
selected: false
});
},
keyPressHandler : function(event){
if (this.state.selected) {
var ul=$(this.refs.autoCompleteList.getDOMNode());
var liSelected = ul.find('li.active');
if(event.keyCode === 40) { //Down Arrow key press
if(liSelected.length>0){
liSelected.removeClass('active');
next = liSelected.next();
if(next.length > 0){
liSelected= next.addClass('active');
}else{
liSelected=ul.find('li').eq(0).addClass('active');
}
}else{
liSelected= ul.find('li').eq(0).addClass('active');
}
}else
if(event.keyCode === 38){//Up Arrow key press
if(liSelected.length>0){
liSelected.removeClass('active');
next = liSelected.prev();
if(next.length > 0){
liSelected=next.addClass('active');
}else{
liSelected=ul.find('li').last().addClass('active');
}
}else{
liSelected=ul.find('li').last().addClass('active');
}
}else
if(event.keyCode === 13){//Enter key press
var selectedValue=liSelected.text();
this.setState({
input: selectedValue,
selected: false
});
}
}
},
matches:function(input) {
const regex = new RegExp(input, 'i');
return this.props.options.filter(function(option) {
return option.match(regex) && option !== input;
});
},
handleFocusChange:function(){//Binding keydown event onFocus textbox
document.addEventListener("keydown", this.keyPressHandler, false);
},
handleFocusOutChange:function(){//Unbinding keydown event onFocusOut textbox
document.removeEventListener("keydown", this.keyPressHandler, false);
},
render : function() {
let autoComplete = null;
var li = [];
var selectedListData=this.matches(this.state.input).map( option => {return option;});
if(selectedListData.length > 0)
{
for(var i=0;i<selectedListData.length;i++) {
li.push(<li className="list-group-item" value={selectedListData[i]} onClick={this.liHandleClick} >{selectedListData[i]}</li> );
}
}
else
{
li.push(<li className="list-group-item">{'No record found'}</li> );
}
if (this.state.selected) {
autoComplete = (<ul ref="autoCompleteList" style={{position:'absolute',width:300+'px'}} className="list-group">{li}</ul>);
}
return (
<div>
<input style={{width:300+'px'}} onChange={this.handleChange.bind(this)} placeholder="Select..."
onFocus={this.handleFocusChange}
onBlur={this.handleFocusOutChange}
value={this.state.input}/>
<div className={'fa fa-circle-o-notch fa-spin'} ></div>
<br />
{autoComplete}
</div>
);
}
});
var optionsData = ['britain', 'ireland', 'norway', 'sweden', 'denmark', 'germany', 'holland', 'belgium', 'france', 'spain', 'portugal', 'italy', 'switzerland'];
React.render(<InputAutoComplete options={optionsData}/>, document.getElementById('autocompleteTest'));