在前端开发过程中,必然有些情况会需要dom元素进行一些节点操作,抛开原生的获取方法,本文将介绍React提供的解决方案,本文所有示例运行版本为react@16.11.0
1. ref
React16.3版本之后React.createRef() API,使用方式如下
class Home extends Component {
constructor(props){
super(props)
this.state = {
}
// ref回调方式获取
this.pRef = null
this.setCallBackRef = element => {
this.pRef = element
}
this.myNode = React.createRef()
this.myPara = React.createRef()
}
componentDidMount(){
console.log(this.myNode.current)
console.log(this.myPara.current)
// 无current
console.log(this.pRef)
}
render() {
return
123
{this.props.number}
}
}
当 ref 被传递给 render 中的元素时,对该节点的引