React参考:Uncaught TypeError:无法将属性'innerHTML'设置为null

时间:2020-09-10 19:45:12

标签: reactjs react-ref

我的构造函数中有这些引用

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

1 个答案:

答案 0 :(得分:1)

出现错误的最可能原因是您的引用未附加到DOM元素。如果您不尝试将这些引用附加到DOM元素,则意味着您未设置引用的初始值。无论哪种方式,该错误都表明您的裁判的值以某种方式为null。因此,您可以:

  • 将您的引用传递到html元素(例如<div ref={myRef} />)中,然后React会自动将您的引用的.current属性设置为相应的DOM节点。
  • 为您的裁判提供一个初始值。 (据我所知,您无法使用createRef为引用提供初始值。您可能需要将组件转换为功能组件,然后可以使用useRef钩子来提供初始值价值给你的裁判。)

要获取有关裁判的更多信息,建议您阅读React's official documentation about refs

相关问题