简体   繁体   English

反应组件类变量访问

[英]react component class variable access

How do I access this the_frame variable? 如何访问此the_frame变量?

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]; 我也尝试过this.the_frame = document.getElementsByClassName("frame")[0]; but can't access the_frame . 但无法访问the_frame Thanks 谢谢

You should use the ref attribute if you would like a reference to the DOM element. 如果要引用DOM元素,则应使用ref属性。

https://facebook.github.io/react/docs/refs-and-the-dom.html 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. React管理渲染,因此您不能保证在您尝试到达元素时就可以访问它。 It in the constructor so your render haven run yet. 它在构造函数中,因此您的渲染还没有运行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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