<!DOCTYPE html> <html> <head> <title>React JS</title> <script src="../build_0.13/react.js"></script> <script src="../build_0.13/JSXTransformer.js"></script> </head> <body> <div id="example"> </div> <script type="text/jsx"> var MySelect = React.createClass({ //初始化组件的值 getInitialState:function(){ return {options:['B']}; }, handleChange:function(event){ var checked = []; var sel = event.target; //获取当前的DOM对象 for(var i=0; i<sel.length; i++){ var option = sel.options[i]; if(option.selected){ checked.push(option.value); } } //设置options的值 this.setState({ options:checked }); }, submitHandler:function(event){ event.preventDefault(); //阻止事件发生 alert(this.state.options); }, render:function(){ return ( <form onSubmit={this.submitHandler}> <select multiple="true" value={this.state.options} onChange={this.handleChange}> <option value="A">First Option</option> <option value="B">Second Option</option> <option value="C">Third Option</option> </select> <br/> <button type="submit">Speak</button> </form> ); } }); //将组件加到对应的元素上 React.render( <MySelect />, document.getElementById('example') ); </script> </body> </html>
注意:
1.使用React里面的值作为html动态的值的时候不要给值添加引号如: value="{this.state.options}" 或者onChange="{this.handleChange}",这两种写法都是错的。