简体   繁体   中英

react component class variable access

How do I access this the_frame variable?

export default class oneApp extends React.Component {
    constructor (props) {
        super(props);
        const the_frame = document.getElementsByClassName("frame")[0];
    }

    oneFunc() {  
        the_frame.style.display = "none"; // How do I access the_frame ?
    }

    twoFunc() {
        the_frame.style.display = "block"; 
    }

    render() {
        return (
            <div className="frame">Hello World</div>
        )
    }
}

I also tried this.the_frame = document.getElementsByClassName("frame")[0]; but can't access the_frame . Thanks

You should use the ref attribute if you would like a reference to the DOM element.

https://facebook.github.io/react/docs/refs-and-the-dom.html

In react you need to use refs. React manages the rendering so you have no guarantee that your element i accessible the moment you are trying to reach it. It in the constructor so your render haven run yet.

More reading https://facebook.github.io/react/docs/refs-and-the-dom.html

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