Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null

家住魔仙堡 提交于 2019-12-13 06:31:25

问题


import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class Game extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.check = this.check.bind(this);
  }


 drawBackground() {
    console.log("worked");
}

  check () {
    this.myRef.current.innerHTML  = "Testing";
    {this.drawBackground()}      
  }

  render() {
    return (
        <div>
          <h1 ref={this.myRef} id="foo">bar</h1>
          {this.check()}
</div>
    );
  }
}

I need to access the text inside h1 tag in the check function, but I get this error Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null. I followed the documentation. Am I missing something?


回答1:


The ref is first set after the first render()

check the demo once demo

You're referring the ref immediately after it is declared, Since the ref object receives the mounted instance of the component as its current.

If you're trying to access the DOM at the same time it's trying to generate it. this.myRef will not return anything because the component has no real DOM representation in render.




回答2:


You need to assign the value to the ref. You are passing ref as a function.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.check = this.check.bind(this);
  }

  state = {
    dom: null
  };

  drawBackground() {
    console.log("worked");
  }

  componentDidMount() {
    this.check();
  }

  check() {
    const innerHTML = ReactDOM.findDOMNode(this.myRef).innerHTML;
    setTimeout(
      () => (ReactDOM.findDOMNode(this.myRef).innerHTML = "TEST"),
      1000
    );
    console.log(innerHTML);
    this.setState({
      dom: innerHTML
    });
    {
      this.drawBackground();
    }
  }

  render() {
    return (
      <div>
        <h1 ref={ref => (this.myRef = ref)} id="foo">
          bar
        </h1>{" "}
        //You need to assign the value of the ref to the instance variable
      </div>
    );
  }
}


来源:https://stackoverflow.com/questions/53955693/reactjs-uncaught-typeerror-cannot-set-property-innerhtml-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!