简体   繁体   中英

Can't read property 'innerHTML' of null

Trying to create a simple text effect In my About class. I'm doing this using React. It keeps telling me that It can't read property innerHTML.

I'm thinking that It can't see the element in render and that's why it thinks it's null. How do I fix this?

class About extends Component
{
  constructor(props){
    super(props)
    this.loading = this.loading.bind(this)
  }

  loading() {
    console.log('i got here')
    let i = 0;
    let txt = this.props.text;
    let speed = 50;
    function typeWriter() {
      if ( i < txt.length){
        document.getElementById("welcome").innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter,speed);
      }
    }
    typeWriter()
  }


    render()
    {
        return(
            <div className="about">
            <h1 id="welcome" onload = {this.loading()}></h1>
            <p>some text</p>
            </div>
        );
    }
}

I just want to change the text in Welcome to display character by character, sort of like a typing effect.

You should use either state or refs. And then run your function on componentDidMount instead of using the onload function. So with refs it would look something like the following:

class About extends Component {
  constructor(props) {
    super(props);
    this.loading = this.loading.bind(this);
    this.elRef = React.createRef();
  }

  componentDidMount() {
    this.loading();
  }

  loading() {
    const el = this.elRef.current;
    let i = 0;
    let txt = 'Hello';
    let speed = 50;
    function typeWriter() {
      if (i < txt.length) {
        el.innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, speed);
      }
    }
    typeWriter();
  }

  render() {
    return (
      <div className="about">
        <h1 ref={this.elRef} />
        <p>some text</p>
      </div>
    );
  }
}

Dom manipulation is a little more tricky with react as it uses a virtual DOM. So when you are trying to manipulate it most of the time the element has not yet been rendered to the actual DOM. So when manipulating a DOM element you need to use react refs React Refs or you can set your values to the state. But in your case that would trigger a re render each time a letter pops up so refs would probably be the best bet for your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM