在vue中,假如想获得DOM元素时,可以用this.$refs.引用名字
在react中也可以像vue中,有类似的写法,如下
为元素添加ref引用
h3ref=test这是h3标签/h3
在页面上获得元素
this.refs.test用ref获得组件的引用
为组件添加ref引用
Textref=hellow/
在页面上用组件的引用
this.refs.hellow
注意点: 只须用ref拿到组件的引用对象,它就是组件的实例对象,因此就能调用这个组件的办法,或者它的属性
react中的三种ref获得DOM节点第一种 ref字符串方法获得Dom节点方法已废弃的原始办法
classDomextendsReact.Component{showInputDom=()={const{userNameInput}=this.refsconsole.log(userNameInput);}render(){return(divinputref=userNameInputtype=text/buttononClick={this.showInputDom}点击显示inpuDom/button/div)}}ReactDOM.render(Dom/,document.getElementById(root))第二种 回调式获得Dom节点方法
开发常用
classDomextendsReact.Component{showInputDom=()={const{userNameInput}=thisconsole.log(userNameInput);}render(){return(div{}{}inputref={(c)={this.userNameInput=c}}type=text/buttononClick={this.showInputDom}点击显示inpuDom/button/div)}}ReactDOM.render(Dom/,document.getElementById(root))第三种 回调式获得Dom节点方法 挂在到自己实例
classDomextendsReact.Component{//挂载到了自己实例上了userNameInput=(c)={this.input1=c;console.log(c);}render(){return(div{}{}{}{}inputref={this.userNameInput}type=text/buttononClick={this.showInputDom}点击显示inpuDom/button/div)}}ReactDOM.render(Dom/,document.getElementById(root))






