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={/* ... *
本文标题为:在 ref 回调之前调用 componentDidMount


基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01