如何解决React参考:Uncaught TypeError:无法将属性'innerHTML'设置为null
我的构造函数中有这些引用
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();
}
这是我的componentDidMount
componentDidMount() {
console.log('ComponentDidMount Start');
if (this.state.modalType === 'lensTintsBlokz') {
this.getLensTintSwatches('blokz');
} else {
this.setState({ lensTintsTabsContainerHidden: false });
this.getLensTintSwatches('sunglasses');
}
}
在getLensTintSwatches函数中-在componentDidMount中调用此函数
this.lensTintStandardSwatchesContainer.current.innerHTML = '';
this.lensTintMirrorSwatchesContainer.current.innerHTML = '';
我遇到以下错误。
Uncaught TypeError: Cannot set property 'innerHTML' of null
我已经尝试了标准React.createRef()和回调样式ref,但是所有ref的当前值都返回null。我在这里做什么错了?
更新:我在各自的传递
ref={this.xyxRef}
作为道具 元素。另一个观察结果-componentDidMount中的console.log不是 根据其他控制台错误触发
这是流程:
Constructor -> Render -> Constructor -> Render -> This ERROR
解决方法
出现错误的最可能原因是您的引用未附加到DOM元素。如果您不尝试将这些引用附加到DOM元素,则意味着您未设置引用的初始值。无论哪种方式,该错误都表明您的裁判的值以某种方式为null。因此,您可以:
- 将您的引用传递到html元素(例如
<div ref={myRef} />
)中,然后React会自动将您的引用的.current
属性设置为相应的DOM节点。 - 为您的裁判提供一个初始值。 (据我所知,您无法使用
createRef
为引用提供初始值。您可能需要将组件转换为功能组件,然后可以使用useRef
钩子来提供初始值价值给你的裁判。)
要获取有关裁判的更多信息,建议您阅读React's official documentation about refs。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。