在 reactjs 中的渲染方法中访问状态值

Jes*_*on 3 javascript reactjs

我是新来的反应。试图将构造函数中的状态传递给我的渲染方法,但我的 h1 不可见,有什么线索吗?

class Mod extends React.Component {

    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };
       //this worked!
        document.title = this.state.title;
    }

    render() {
        return(
            <div>
                <h1>{this.title}</h1>
            </div>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

May*_*kla 5

原因是您在 state 中定义标题,将 state 视为object,并且您在其中定义的所有变量都将成为键值,并且要访问它们,您必须像这样使用它:this.state.variable_name,使用这个:

class Mod extends React.Component {

    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };

    }

    render() {
        return(
            <div>
                <h1>{this.state.title}</h1>
            </div>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

document.title='name'工作的原因是,您将其定义为全局变量,并且您可以直接通过document.title.

文件:

Document是一个对象。全局对象document代表HTML当前浏览器窗口中显示的文档。Web 浏览器将具有 JavaScript 引擎。该引擎将为开发人员提供一些运行时对象,例如documentwindow 进行交互。