react------refs 淩亂°似流年 2023-06-06 13:28 4阅读 0赞 refs:组件内的标签都可以定义ref属性来标识自己 在组件中科院通过this.refs.refName来获取对应的真实DOM对象 用于操作指定的reg属性的Dom元素对象 <input type="text" > <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> class RefCom extends React.Component{ constructor(props){ super(props); // 修改this(这里的this为组件的实例对象) 强制绑定this call apply bind this.handleClick = this.handleClick.bind(this) } handleClick(){ //获取input输入的内容 var val = this.refs.msg.value alert(val) } render(){ return ( <div> <input type="text" name="" id="" ref="msg"/> <button onClick={this.handleClick}>数据</button> </div> ) } } ReactDOM.render(<RefCom />,document.getElementById('app')) </script> </body> </html> render中的this指向实例对象,自定义函数中的this指向null,所以需要给函数绑定this <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> class RefCom extends React.Component{ constructor(props){ super(props); // 修改this(这里的this为组件的实例对象) 强制绑定this call apply bind this.handleClick = this.handleClick.bind(this) } handleClick(){ //获取input输入的内容 var val = this.refs.msg.value alert(val) } blurClick(event){ alert(event.target.value) } render(){ return ( <div> <input type="text" name="" id="" ref="msg"/> <input type="text" onBlur={this.blurClick} name="" id="" placeholder="失去焦点触发" /> <button onClick={this.handleClick}>数据</button> </div> ) } } ReactDOM.render(<RefCom />,document.getElementById('app')) </script> </body> </html>
还没有评论,来说两句吧...