简体   繁体   中英

Cannot read property 'style' of null in React

I want to make this work. the same thing is work but this not works.
check this out.
as you can see, the backgroundScroll is OK its working,
but a while later, i add sth , its not working .below is error message.
Uncaught TypeError: Cannot read property 'style' of null at eval

 import React, { createRef, PureComponent } from 'react'; class History extends PureComponent { backgroundScroll = createRef() sth=createRef() //error handelScroll = () => { let scrollTop = document.body.scrollTop this.backgroundScroll.current.style.backgroundPositionY = `${scrollTop / 3}px` } clickRight=()=>{ this.sth.current.style.animation='opacityChange 2s' } componentDidMount() { window.addEventListener('scroll', this.handelScroll); } componentWillUnmount() { window.removeEventListener('scroll', this.handelScroll); } render() { return ( <> {this.state.picture && <div> <div ref={this.sth} onClick={this.clickRight}></div> </div> } <header ref={this.backgroundScroll}><header> </> ) } } export default History

The point of the constructor is not to solve the problem, rather a best practice that you should from now put the refs in there, as I showed in my earlier comment.

Try this in your clickRight -method:

clickRight = () => {
    if(this.state.picture) {
        this.sth.current.style.animation='opacityChange 2s'
    }
}

I feel like some code are missing here, since you're referring to this.state.picture in the render method. My guess is that the clickRight method tries to access the sth.style property when it doesn't reference a dom-element (IE if this.state.picture doesn't exist, the div including the sth ref won't be rendered.

First of all I would move the creation of the refs to the constructor:

class History extends PureComponent {
constructor() {
    super();
    this.backgroundScroll = createRef();
    this.sth = createRef();
    }
}

Then try to remove the conditional render and see if it works.

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