- 通过React.createRef → ref对象
- 通过元素的ref属性可以附加到React元素上
- 一般通过构造器中给this的属性赋值一个ref,方便整个组件使用
- ref只要传递到react元素中,就可以利用ref的current属性访问到该真实DOM节点
- ref在componentDidMount和componentDidUpdate触发前更新
current里是null的现象
- 由于打印时,
this.modalRef
才刚刚声明,current是null,但是current是个引用值,展开时访问的是最后的结果
class Modal extends React.Component {
constructor(props) {
super(props)
this.modalRef = React.createRef()
console.log('刚创建时', this.modalRef)
}
componentDidMount() {
console.log('componentDidMount', this.modalRef)
}
componentDidUpdate() {
console.log