React 中 ref 的使用
程序员文章站
2022-06-28 18:31:06
实例:获取button元素离页面顶部的距离 ref写在html元素上 import React,{Component,Fragment} from 'react'; import Child from './Child'; class Counter extends Component{ const ......
实例:获取button元素离页面顶部的距离
ref写在html元素上
import react,{component,fragment} from 'react'; import child from './child'; class counter extends component{ constructor(props){ super(props); this.addcount=this.addcount.bind(this); this.state={ counter:1 } } addcount(){ console.log(this.button); console.log(this.button.clienttop); this.setstate({ counter:this.state.counter+1 }) } render(){ return( <fragment> <button onclick={this.addcount} ref={button=>this.button=button}>点击</button> <child num={this.state.counter}/> </fragment> ) } } export default counter;
ref写在组件上,获取的是组件的实例
import react,{component,fragment} from 'react'; import child from './child'; class counter extends component{ constructor(props){ super(props); this.addcount=this.addcount.bind(this); this.state={ counter:1 } } addcount(){ console.log(this.child); this.setstate({ counter:this.state.counter+1 }) } render(){ return( <fragment> <button onclick={this.addcount}>点击</button> <child num={this.state.counter} ref={child=>this.child=child}/> </fragment> ) } } export default counter;
总结:ref写在html标签上,获取的是dom节点
ref写在组件标签上,获取的是组件的js实例
setstate异步,实例:
import react,{component,fragment} from 'react'; class counter extends component{ constructor(props){ super(props); this.addcount=this.addcount.bind(this); this.state={ counter:1 } } addcount(){ console.log(this.div.innerhtml); this.setstate({ counter:this.state.counter+1 }) console.log(this.div.innerhtml); } render(){ return( <fragment> <button onclick={this.addcount}>点击</button> <div ref={div=>this.div=div}>{this.state.counter}</div> </fragment> ) } } export default counter;
可以看到两次输出的都是1,证明setstate操作是异步执行的
解决方法:
import react,{component,fragment} from 'react'; class counter extends component{ constructor(props){ super(props); this.addcount=this.addcount.bind(this); this.state={ counter:1 } } addcount(){ console.log(this.div.innerhtml); this.setstate(()=>{ return{ counter:this.state.counter+1 } },()=>{ console.log(this.div.innerhtml); }) } render(){ return( <fragment> <button onclick={this.addcount}>点击</button> <div ref={div=>this.div=div}>{this.state.counter}</div> </fragment> ) } } export default counter;
这种写法,第二次打印会在setstate执行完毕之后再执行
结果:
上一篇: 教你如何显示PPT演示文稿的打印预览屏幕