auto_complete.html
<!DOCTYPEhtml> <html> <head> <Metacharset="UTF-8"/> <title>HelloReact!</title> <linkhref="css/auto_complete.css"rel="stylesheet"/> <scriptsrc="jslib/jquery-1.11.3.min.js"></script> <scriptsrc="jslib/react.js"></script> <scriptsrc="jslib/react-dom.js"></script> <scriptsrc="jslib/browser-2.8.23.min.js"></script> </head> <body> <divid="autocomplete"></div> <scripttype="text/babel"src="js/auto_complete.js"></script> </body> </html>
css/auto_complete.js
varAutoComplete=React.createClass({ list:["apple","banana","grape","org","orange"],timeout:null,getInitialState:function(){ return{ open:null,matchedItems:this.generateLiHtml(this.list) } },generateLiHtml:function(list){ varmatchedItems=[]; for(vari=0;i<list.length;i++){ matchedItems.push(<likey={i}onClick={this.clickHandler}>{list[i]}</li>); } returnmatchedItems; },clickHandler:function(e){ e.stopPropagation(); e.preventDefault(); varliItem=$(e.target); varcontent=$(liItem).html(); $(ReactDOM.findDOMNode(this)).find("input").val(content); this.setState({open:""}); },keyUpHandler:function(e){ e.stopPropagation(); clearTimeout(this.timeout); varval=e.target.value; varthat=this; this.timeout=setTimeout(function(){ varresult=[]; for(vari=0;i<that.list.length;i++){ varitem=that.list[i]; if(item.startsWith(val)){ result.push(item); } } varopen=null; if(result.length>0){ open="open"; } varmatchedItems=that.generateLiHtml(result); that.setState({matchedItems:matchedItems,open:open}); },300); },render:function(){ return( <divclassName="auto-complete"> <inputtype="text"onKeyUp={this.keyUpHandler}/> <divclassName={this.state.open}> <ul> {this.state.matchedItems} </ul> </div> </div> ); } }); ReactDOM.render( <AutoComplete/>,$("#autocomplete")[0] );
css/auto_complete.css
.auto-complete{ width:200px; } .auto-completeinput{ width:100%; Box-sizing:border-Box; } .auto-complete>div{ display:none; padding-top:10px; } .auto-complete>div.open{display:block;} .auto-complete>divul{ padding:0; margin:0; list-style-type:none; border:1pxsolid#ccc; } .auto-complete>divulli{ height:30px; line-height:30px; border-bottom:1pxsolid#ccc; padding-left:10px; } .auto-complete>divulli:hover{ background-color:#eaeaea; cursor:pointer; } .auto-complete>divulli:last-child{ border-bottom:none; }原文链接:https://www.f2er.com/react/307101.html