react jsx 编写autocomplete实现
发布时间:2020-12-15 04:38:36 所属栏目:百科 来源:网络整理
导读:auto_complete.html !DOCTYPEhtmlhtmlheadmetacharset="UTF-8"/titleHelloReact!/titlelinkhref="css/auto_complete.css"rel="stylesheet"/scriptsrc="jslib/jquery-1.11.3.min.js"/scriptscriptsrc="jslib/react.js"/scriptscriptsrc="jslib/react-dom.js"/
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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |