auto_complete.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello React!</title> <link href="css/auto_complete.css" rel="stylesheet"/> <script src="jslib/jquery-1.11.3.min.js"></script> <script src="jslib/react.js"></script> <script src="jslib/react-dom.js"></script> <script src="jslib/browser-2.8.23.min.js"></script> </head> <body> <div id="autocomplete"></div> <script type="text/babel" src="js/auto_complete.js"></script> </body> </html>
css/auto_complete.js
var AutoComplete = React.createClass({ list:["apple","banana","grape","org","orange"], timeout:null, getInitialState:function(){ return { open:null, matchedItems:this.generateLiHtml(this.list) } }, generateLiHtml:function(list){ var matchedItems = []; for(var i=0;i<list.length;i++){ matchedItems.push(<li key={i} onClick={this.clickHandler}>{list[i]}</li>); } return matchedItems; }, clickHandler:function(e){ e.stopPropagation(); e.preventDefault(); var liItem = $(e.target); var content = $(liItem).html(); $(ReactDOM.findDOMNode(this)).find("input").val(content); this.setState({open:""}); }, keyUpHandler:function(e){ e.stopPropagation(); clearTimeout(this.timeout); var val = e.target.value; var that = this; this.timeout = setTimeout(function(){ var result = []; for(var i=0;i<that.list.length;i++){ var item = that.list[i]; if(item.startsWith(val)){ result.push(item); } } var open = null; if(result.length>0){ open = "open"; } var matchedItems = that.generateLiHtml(result); that.setState({matchedItems:matchedItems,open:open}); },300); }, render: function() { return ( <div className="auto-complete"> <input type="text" onKeyUp={this.keyUpHandler}/> <div className={this.state.open}> <ul> {this.state.matchedItems} </ul> </div> </div> ); } }); ReactDOM.render( <AutoComplete/>, $("#autocomplete")[0] );
css/auto_complete.css
.auto-complete{ width:200px; } .auto-complete input{ width:100%; box-sizing:border-box; } .auto-complete>div{ display:none; padding-top:10px; } .auto-complete>div.open{display:block;} .auto-complete>div ul{ padding:0; margin:0; list-style-type: none; border:1px solid #ccc; } .auto-complete>div ul li{ height:30px; line-height: 30px; border-bottom:1px solid #ccc; padding-left:10px; } .auto-complete>div ul li:hover{ background-color:#eaeaea; cursor:pointer; } .auto-complete>div ul li:last-child{ border-bottom:none; }