07 React 组件三大属性-----refs
需求: 自定义组件, 功能说明如下:
1. 界面如页面所示
2. 点击按钮, 提示第一个输入框中的值
3. 当第2个输入框失去焦点时, 提示这个输入框中的值
第一步,初始化静态组件,并渲染组件标签
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/react.development.js"></script> <script src="../js/react-dom.development.js"></script> <script src="../js/babel.min.js"></script> </head> <body> <div id="test"></div> </body> </html> <script type="text/babel"> class MyComponent extends React.Component{ render(){ return( <div> <input type="text"/> <button>提示输入的值</button> <br/> <input type="text" placeholder="失去焦点提示内容"/> </div> ) } } ReactDOM.render(<MyComponent/>,document.getElementById("test")); </script>
第二步,做交互,点击按钮弹出输入框中的值,以及失去焦点是弹出输入框中的值
前者操作的DOM元素和触发事件的元素不是同一个,后者操作DOM元素和触发事件的元素都是 input,后者可以使用 event.target 获取值
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 <script src="../js/react.development.js"></script> 8 <script src="../js/react-dom.development.js"></script> 9 <script src="../js/babel.min.js"></script> 10 </head> 11 <body> 12 <div id="test"></div> 13 </body> 14 </html> 15 <script type="text/babel"> 16 17 class MyComponent extends React.Component{ 18 constructor(props) { 19 super(props); 20 this.handleClick1 = this.handleClick1.bind(this); 21 this.handleClick2 = this.handleClick2.bind(this); 22 this.handleBlur = this.handleBlur.bind(this); 23 } 24 25 render(){ 26 return( 27 <div> 28 <input type="text" ref="content"/> 29 <button onClick={this.handleClick1}>提示输入的值(方式1)</button> 30 <br/> 31 <input type="text" ref={input=>this.input=input}/> 32 <button onClick={this.handleClick2}>提示输入的值(方式2,官方推荐)</button> 33 <br/> 34 <input type="text" placeholder="失去焦点提示数据" onBlur={this.handleBlur}/> 35 </div> 36 ) 37 } 38 39 handleClick1() { 40 alert(this.refs.content.value); 41 42 } 43 handleClick2() { 44 alert(this.input.value); 45 46 } 47 handleBlur(event){ 48 alert(event.target.value); 49 } 50 51 } 52 ReactDOM.render(<MyComponent/>,document.getElementById("test")); 53 </script>