我是新手。试图将构造函数中的状态传递到我的渲染方法中,但我的 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
访问它们>.
Document
is an object. The global objectdocument
represents theHTML
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 asdocument
andwindow
to interact with.
关于javascript - 在 reactjs 中的渲染方法中访问状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111236/