实例:获取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执行完毕之后再执行
结果: