react 编写autocomplete实现(非jsx)

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.min.js"></script>
    <script src="jslib/react-dom.min.js"></script>
</head>
<body>

	<div id="autocomplete"></div>

	<script src="js/auto_complete.js"></script>

</body>
</html>

js/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++){
	      
        var item = React.DOM.li({key:i,onClick:this.clickHandler},list[i]);

        matchedItems.push(item);
    }
    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  React.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-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;
}


你可能感兴趣的:(html,js,autocomplete,react)