以下代码未显示当前日期和时间的预期输出
class Mydate extends React.Component{
constructor(props){
super(props);
this.state={
date:new Date(),
showMessage: false
}
this.show=this.show.bind(this);
}
show(){
this.setState({showMessage: true});
return this.state.date;
}
render(){
return(
<div>
<h2>Hello World!!</h2>
{this.state.showMessage && <p>{this.state.date}</p>}
<button onClick={this.show}>show Date</button>
</div>
);
}
}
为什么 show() 在这里不起作用。你能帮我知道问题出在哪里吗
最佳答案
正如我检查的 this.state.date
是一个 js Date 对象,当它在文档中打印时,它试图将其转换为字符串以确保它是 jsx 中的有效子对象,并且获取失败。使用如下内容
<p>{this.state.date.toString()}</p>
关于javascript - 查看按钮点击 react 中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62528071/