【发布时间】:2020-12-29 08:45:57
【问题描述】:
我的构造函数中有这些引用
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,但是所有 refs 的当前值都返回 null。我在这里做错了什么?
更新:我将
ref={this.xyxRef}作为相应的道具传递 元素。另一个观察 - componentDidMount 中的 console.log 不是 触发,基于其他控制台错误
这是流程:
Constructor -> Render -> Constructor -> Render -> This ERROR
【问题讨论】:
-
您是否将参考附加到实际元素上?还要记住,必须渲染元素才能设置 ref。这不能总是得到保证,因此最好检查 refs 是否存在。
-
@JohannesKlauß 是的,裁判附在他们各自的元素上。如何验证我的 JSX 是否被渲染?
-
检查
this.ref.current是否不为空。 -
@JohannesKlauß 无效
-
那么要么没有附加 ref,要么元素还没有渲染。所以你必须在以后设置 ref。