一、不可控组件
1.简介
2.代码
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>琛ㄥ崟璇﹁В</title> 6 </head> 7 <body> 8 <script src="./react-0.13.2/react-0.13.2/build/react.js"></script> 9 <script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script> 10 <script type="text/jsx"> 11 // var MyForm = React.createClass({ 12 // render: function () { 13 // return <input 14 // type="text" defaultValue="Hello World!" />; 15 // } 16 // }); 17 var MyForm = React.createClass({ 18 submitHandler: function (event) { 19 event.preventDefault(); 20 var helloTo = React.findDOMNode(this.refs.helloTo).value; 21 alert(helloTo); 22 }, 23 render: function () { 24 return <form onSubmit={this.submitHandler}> 25 <input 26 ref="helloTo" 27 type="text" 28 defaultValue="Hello World!" /> 29 <br /> 30 <button type="submit">Speak</button> 31 </form>; 32 } 33 }); 34 React.render(<MyForm></MyForm>, document.body); 35 </script> 36 </body> 37 </html>
二、可控组件
1.简介
2.代码
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>表单详解</title> 6 </head> 7 <body> 8 <script src="./react-0.13.2/react-0.13.2/build/react-with-addons.js"></script> 9 <script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script> 10 <script type="text/jsx"> 11 var MyForm = React.createClass({ 12 getInitialState: function () { 13 return { 14 helloTo: "Hello World!" 15 }; 16 }, 17 handleChange: function (event) { 18 this.setState({ 19 helloTo: event.target.value 20 }); 21 }, 22 submitHandler: function (event) { 23 event.preventDefault(); 24 alert(this.state.helloTo); 25 }, 26 render: function () { 27 return <form onSubmit={this.submitHandler}> 28 <input type="text" value={this.state.helloTo} onChange={this.handleChange} /> 29 <br /> 30 <button type="submit">Speak</button> 31 </form>; 32 } 33 }); 34 React.render(<MyForm></MyForm>, document.body); 35 </script> 36 </body> 37 </html>
时间: 2024-10-07 06:24:12