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.min.js"></script> <scriptsrc="jslib/react-dom.min.js"></script> </head> <body> <divid="autocomplete"></div> <scriptsrc="js/auto_complete.js"></script> </body> </html>
js/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++){ varitem=React.DOM.li({key:i,onClick:this.clickHandler},list[i]); matchedItems.push(item); } 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(){ returnReact.DOM.div( {className:"auto-complete"},React.DOM.input({type:"text",onKeyUp:this.keyUpHandler}),React.DOM.div( {className:this.state.open},React.DOM.ul(null,this.state.matchedItems ) ) ); } }); ReactDOM.render( React.createElement(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/307100.html