Javascript 请参见react中按钮单击的日期

Javascript 请参见react中按钮单击的日期,javascript,reactjs,Javascript,Reactjs,下面的代码未显示当前日期和时间的预期输出 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

下面的代码未显示当前日期和时间的预期输出

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>
    );
  }
}
    
类Mydate扩展React.Component{
建造师(道具){
超级(道具);
这个州={
日期:新日期(),
showMessage:false
}
this.show=this.show.bind(this);
}
show(){
this.setState({showMessage:true});
返回此.state.date;
}
render(){
返回(
你好,世界!!
{this.state.showMessage&&{this.state.date}

} 放映日期 ); } }

为什么show()在这里不起作用。当我选中此
时,您能帮助我知道问题出在哪里吗。state.date
是一个js日期对象,当它在文档中打印时,它需要将其转换为字符串以确保它在jsx中是有效的子对象,并且失败。使用下面的东西

<p>{this.state.date.toString()}</p>
{this.state.date.toString()}


当前,日期对象被呈现为
标记中的对象。对象不能作为“子对象”传递给jsx标记

最简单的解决方法是在
标记中显示日期时,使用toString()方法将日期转换为字符串

   render(){
    return(
      <div>
        <h2>Hello World!!</h2>
         {this.state.showMessage && <p>{this.state.date.toString()}</p>} 
        <button onClick={this.show}>show Date</button>
      </div>
    );
  }
render(){
返回(
你好,世界!!
{this.state.showMessage&&{this.state.date.toString()}

} 放映日期 ); }

我希望这有帮助


干杯

@g如果我只是在show()中返回这个.state.date.toString(),而不使用条件呈现,是否正确。我看不见那条路output@RayErd否。onClick事件不使用show()的返回值。您不需要在show函数中具有返回。当this.state.showMessage为false时,JS不会检查&&conditional render语句的第二部分,因此不会呈现JSX。在您的用例中,调用show()将this.state中的showMessage设置为true,导致react重新启动组件,并在下一次渲染时计算&&的第二部分,该部分仅返回JSX并显示日期字符串。