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(.button); console.log(.button.clientTop); .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,1)">.child); this.addCount}>点击</button> <Child num={this.state.counter} ref={child=>this.child=child}/> </Fragment> default Counter;
setState异步,实例:
import React,1)">.div.innerHTML); }) console.log(.div.innerHTML); } render(){ this.addCount}>点击</button> <div ref={div=>this.div=div}>{this.state.counter}</div> </Fragment> default Counter;
可以看到两次输出的都是1,证明setState操作是异步执行的
解决方法:
import React,1)">this.setState(()=>{ { counter: } },()=>{ console.log(.div.innerHTML); }) } render(){ default Counter;
这种写法,第二次打印会在setState执行完毕之后再执行
结果: