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

标签 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>
        )
    }
}

最佳答案

原因是您在状态中定义标题,将状态视为对象,并且您在其中定义的所有变量都将是键值,要访问它们,您必须使用它像这样: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>
        )
    }
}

document.title='name' 起作用的原因是,您将其定义为全局变量,您可以直接通过 document.title 访问它们>.

Doc:

Document is an object. The global object document represents the HTML document which is displayed in the current browser window. The web browser will have JavaScript engine. That engine will provide the developer with some runtime objects, such as document and window to interact with.

关于javascript - 在 reactjs 中的渲染方法中访问状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111236/

相关文章:

javascript - 尝试将数据推送到 JSON 数组

javascript - this.setState 报错

javascript - React 递归函数来渲染组件

javascript - 将选项作为对象数组进行多项选择

javascript - slot-scope 和 v-for 的组合使用不明确(v-for 具有更高的优先级)。对作用域槽使用包装器以使其更清晰

javascript - 记录通过函数生成的类(混合)

javascript - 数组未定义 - React Redux

javascript - '& > *' in React' s 样式

javascript - 难以分配折扣

javascript - 需要帮助将数组显示到几个文本框