[英]React Ref: Uncaught TypeError: Cannot set property 'innerHTML' of null
I have these refs in my constructor我的构造函数中有这些引用
constructor(props) {
super(props);
//All Refs
this.sunglassesTintsTab = React.createRef();
this.gradientTintsTab = React.createRef();
this.fashionTintsTab = React.createRef();
this.lensTintStandardSwatchesContainer = React.createRef();
this.lensTintMirrorSwatchesContainer = React.createRef();
}
And this is my componentDidMount这是我的 componentDidMount
componentDidMount() {
console.log('ComponentDidMount Start');
if (this.state.modalType === 'lensTintsBlokz') {
this.getLensTintSwatches('blokz');
} else {
this.setState({ lensTintsTabsContainerHidden: false });
this.getLensTintSwatches('sunglasses');
}
}
In the getLensTintSwatches function - this is being called in componentDidMount在 getLensTintSwatches 函数中 - 这在 componentDidMount 中被调用
this.lensTintStandardSwatchesContainer.current.innerHTML = '';
this.lensTintMirrorSwatchesContainer.current.innerHTML = '';
I'm getting the following error.我收到以下错误。
Uncaught TypeError: Cannot set property 'innerHTML' of null
I have tried both the standard React.createRef() and callback style ref but the current value of all the refs is returning null.我已经尝试了标准的 React.createRef() 和回调样式 ref,但所有 refs 的当前值都返回 null。 What am I doing wrong here?我在这里做错了什么?
UPDATE: I'm passing
ref={this.xyxRef}
as prop in the respective elements.更新:我将ref={this.xyxRef}
作为相应元素中的道具传递。Another observation- The console.log in componentDidMount is not triggered, based on other console errors另一个观察 - 未触发 componentDidMount 中的 console.log,基于其他控制台错误
This is the flow:这是流程:
Constructor -> Render -> Constructor -> Render -> This ERROR
The most likely reason why you are getting the error is that your refs are not attached to a DOM element .您收到错误的最可能原因是您的 refs 未附加到 DOM 元素。 If you are not trying to attach these refs to a DOM element, that means that you didn't set the initial values of your refs.如果您没有尝试将这些 refs 附加到 DOM 元素,则意味着您没有设置 refs 的初始值。 Either way, the error says that your refs' values are null somehow.无论哪种方式,错误都表明您的参考值以某种方式为空。 So, you can either:因此,您可以:
<div ref={myRef} />
), then React will automatically set your ref's .current
property to the corresponding DOM node.将你的 refs 传递给一个 html 元素(例如<div ref={myRef} />
),然后 React 会自动将你的 ref 的.current
属性设置为相应的 DOM 节点。createRef
. You might need to convert your component into a functional component and then you can use useRef
hook to give initial value to your refs.) (据我所知,您无法使用createRef
为 refs 提供初始值。您可能需要将您的组件转换为功能组件,然后您可以使用useRef
钩子为您的 refs 提供初始值。)To have more info about refs, I suggest you to read the React's official documentation about refs .要了解有关 refs 的更多信息,我建议您阅读React 关于 refs 的官方文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.