【发布时间】:2017-10-19 20:40:18
【问题描述】:
问题
我正在使用内联函数定义设置反应 ref
render = () => {
return (
<div className="drawer" ref={drawer => this.drawerRef = drawer}>
那么在componentDidMount 中没有设置DOM 引用
componentDidMount = () => {
// this.drawerRef is not defined
我的理解是ref 回调应该在挂载期间运行,但是添加console.log 语句显示componentDidMount 被调用在 ref 回调函数之前。
我看过的其他代码示例,例如 github 上的 this discussion 表明相同的假设,componentDidMount 应该在render 中定义的任何 ref 回调之后调用 ,甚至stated in the conversation
所以 componentDidMount 在所有 ref 回调完成后被触发 被处决了?
是的。
我正在使用反应 15.4.1
我尝试过的其他方法
为了验证 ref 函数是否被调用,我尝试在类中定义它
setDrawerRef = (drawer) => {
this.drawerRef = drawer;
}
然后在render
<div className="drawer" ref={this.setDrawerRef}>
在这种情况下,控制台日志显示回调确实被调用之后 componentDidMount
【问题讨论】:
-
我可能是错的,但是当您使用箭头函数进行渲染时,它将从您的类之外的词法范围捕获
this的值。尝试摆脱类方法的箭头函数语法,看看是否有帮助。 -
@GProst 这就是我的问题的本质。我将 console.log 放在两个函数中,并且 componentDidMount 首先运行,然后是 ref 回调。
-
刚刚遇到了类似的问题——对我们来说,基本上,我们在最初的
render上错过了它,因此需要利用componentDidUpdate,因为componentDidMount不是更新的一部分@ 987654324@。可能不是您的问题,但认为它可能值得作为潜在的解决方案提出。 -
与 React 16 相同。文档明确指出
ref callbacks are invoked before componentDidMount or componentDidUpdate lifecycle hooks.但这似乎不是真的:( -
1. ref 箭头声明为:
ref = {ref => { this.drawerRef = ref }}2. 甚至在 componentDidMount 之前调用 refs;当您的案例中的 div 被渲染时,只能在初始渲染后访问 ref 。因此,您必须能够访问下一级的 ref,即在 componentWillReceiveProps 中使用this.drawerRef3。如果您尝试在初始挂载之前访问,您将只能获得未定义的 ref 值。
标签: javascript reactjs