【问题标题】:React Ref: Uncaught TypeError: Cannot set property 'innerHTML' of nullReact Ref:未捕获的 TypeError:无法将属性“innerHTML”设置为 null
【发布时间】: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。

标签: reactjs react-ref


【解决方案1】:

您收到错误的最可能原因是您的 ref 没有附加到 DOM 元素。如果您不尝试将这些 ref 附加到 DOM 元素,则意味着您没有设置 ref 的初始值。无论哪种方式,错误都表明您的参考值以某种方式为空。因此,您可以:

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

要了解更多关于 refs 的信息,我建议你阅读React's official documentation about refs

【讨论】:

  • 我就像你提到的那样传递了 refs 并且使它成为一个功能组件不是一个选项。
  • 你能在 CodeSandbox 中重现这个案例吗?
  • 这是工作代码,所以我无法复制组件的深度,因为它依赖于一堆东西。我希望 StackOverflow 有一个缩放呼叫选项来寻求帮助。
  • 如果你确定你正确地附加了你的 refs,检查在 mount 时可能没有附加 refs 的情况。我强烈建议你看看这个答案:stackoverflow.com/a/50019873/10917390
猜你喜欢
  • 2023-04-09
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
相关资源
最近更新 更多