无法在初始渲染中找到 ref [英] Cannot find ref on initial render
问题描述
我刚刚在官方文档中看到 componentDidUpdate 在第一次渲染时没有被调用,我想也许这就是为什么我的这个组件在第一次渲染时没有定义 dom 的原因.
这是一个弹出模式,当需要编辑页面时弹出.
有没有其他办法可以解决这个问题?
componentDidUpdate() {this.renderSingularForm();}renderSingularForm() {让 dom = ReactDOM.findDOMNode( this.refs.singularForm );if ( this.props.pageObjToEdit && dom ) {//不会在第一次渲染时进入这里,因为 DOM 为 NULLcreateForm( window, dom, this.props.pageObjToEdit );}}使成为() {如果(this.props.pageObjToEdit){返回 (<div><div ref="singularForm"/>
);}别的 {返回空;}}
这是一个关于你如何使用 refs 的问题.你不应该再使用字符串引用了,因为它们 即将弃用.大多数人现在使用内联引用( ref={ref => this.input = ref}
),但是当你这样做时,组件第一次渲染它会收到一个 空
值.然后在第二次渲染时,refs 将正确分配给 DOM 元素.
为了解决这个问题,你应该为 ref
属性提供一个类方法,而不是一个内联函数.
示例:
这个:
render() {返回 (...<div ref="singularForm";/>...)}
应该是:
applyRef = ref =>{this.singularForm = ref;}使成为() {返回 (...<div ref={this.applyRef}/>...)}
当您使用类方法来应用 ref 时,它只会在实际元素添加到 dom 时被调用一次,因此您不应再获得初始的 null
值.
更新 10/18:
您现在可以使用新的React.createRef
来创建你的引用.
I just read in the official documents that componentDidUpdate isn't called on first render and I think maybe that's why dom isn't defined the first time this Component of mine is rendered.
This is a pop up modal that pops up when a page needs to be edited.
Is there any other way I can go about this?
componentDidUpdate() {
this.renderSingularForm();
}
renderSingularForm() {
let dom = ReactDOM.findDOMNode( this.refs.singularForm );
if ( this.props.pageObjToEdit && dom ) {
// DOESN'T GO HERE ON FIRST RENDER BECAUSE DOM IS NULL
createForm( window, dom, this.props.pageObjToEdit );
}
}
render() {
if ( this.props.pageObjToEdit ) {
return (
<div>
<div ref="singularForm" />
</div>
);
}
else {
return null;
}
}
This is an issue with how you are using refs. You shouldn't be using string refs anymore since they will be deprecated soon. Most people are now using an inline ref ( ref={ref => this.input = ref}
), but when you do that, the first time the component renders it will receive a null
value. Then on the second render, the refs will be correctly assigned with the DOM element.
To get around this, you should supply a class method to the ref
prop instead of an inline function.
Example:
This:
render() {
return (
...
<div ref="singularForm" />
...
)
}
Should be:
applyRef = ref => {
this.singularForm = ref;
}
render() {
return (
...
<div ref={this.applyRef} />
...
)
}
When you use a class method to apply a ref, it only gets called once when the actual element has been added to the dom, so you shouldn't get the initial null
values anymore.
UPDATE 10/18:
You can now avoid this problem altogether using the new React.createRef
to create your refs.
这篇关于无法在初始渲染中找到 ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!