componentDidMount called BEFORE ref callback(在 ref 回调之前调用 componentDidMount)
问题描述
问题
我正在设置一个反应 ref代码> 使用内联函数定义
render = () =>{返回 (<div className="drawer" ref={drawer =>this.drawerRef = 抽屉}>
那么在 componentDidMount
中没有设置 DOM 引用
componentDidMount = () =>{//this.drawerRef 没有定义
我的理解是 ref
回调应该在挂载期间运行,但是添加 console.log
语句显示 componentDidMount
被称为 before ref 回调函数.
我看过的其他代码示例,例如 github 上的 this discussion 表明同样的假设,componentDidMount
应该在 render
中定义的任何 ref
回调之后调用,甚至是 在对话中陈述
所以 componentDidMount 在所有 ref 回调完成后被触发被处决了?
是的.
我正在使用反应 15.4.1
我尝试过的其他方法
为了验证 ref
函数是否被调用,我尝试在类上定义它
setDrawerRef = (抽屉) =>{this.drawerRef = 抽屉;}
然后在渲染
<div className="drawer" ref={this.setDrawerRef}>
在这种情况下,控制台日志显示回调确实在 componentDidMount
简答:
React 保证在 componentDidMount
或 componentDidUpdate
钩子之前设置 refs.但仅适用于实际被渲染的孩子.
componentDidMount() {//可以在这里使用任何 refs}组件DidUpdate() {//可以在这里使用任何 refs}使成为() {//只要那些 refs 被渲染了!返回 <div ref={/* ... *