繁体   English   中英

期待为React Button onClick事件输出组件的时间戳

[英]Looking to output timestamp to component for React Button onClick event

我还在学习Javascript和React的世界 - 请原谅我缺乏知识:)

我试图基本上过滤每天的点击次数,即使用时间戳。 我最初的想法过程是这样的:

  • onClick函数中,将time设置为moment().toDate()
  • this.state.time输出到单独的stats.js文件中的React组件

console.log(moment().toDate())会在按下按钮时输出时间戳,这很好,但是我无法进行渲染。

有任何想法吗?

到目前为止我的App.js文件:

import Layout from '../components/MyLayout.js'
import Header from '../components/Header.js'
import Link from 'next/link'
import React, { Component } from "react";
import { spring } from 'popmotion';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
const moment = require('moment');
import LinearProgress from '@material-ui/core/LinearProgress';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      response: undefined
    };
    this.incrementCounter = this.incrementCounter.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    this.setState({
      count: parseInt(localStorage.getItem("count")) || 0
    });
  }

  incrementCounter() {
    const count = this.state.count + 1;
    localStorage.setItem("count", count);
    this.setState({
      count: count
    });
  }

  handleSubmit = (event) => {
    event.preventDefault();
    fetch('/', { method: 'POST' })
    .then(response => response.text())
    .then(textValue => this.setState({ response: textValue }))
    .then(time => this.setState({ time: moment().toDate() }))
    .then(console.log(moment().toDate()));
  }

  render() {
    return (
        <main>
            <Header />
              <div style={{paddingTop: "150px"}}>
                <Typography variant="title" color="inherit">
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <h1 style={{ fontFamily:"Arial", fontSize:"50px" }}>Magic 8 Ball</h1>
                  </div>
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <form className="question-input" onSubmit={this.handleSubmit}>
                      <TextField
                        id="inputquestion"
                        autoComplete="off"
                        placeholder="Ask your question..."
                        margin="normal"
                        style={{ width:"200px", paddingRight:"10px" }}
                      />
                      <Button
                        variant="contained"
                        type="submit"
                        color="primary"
                        onClick={ this.incrementCounter.bind(this) }
                        id="submitquestion"
                        style={{ width: "100px", fontSize:17 }}>Shake Me!
                      </Button>
                    </form>
                  </div>
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <p>Magic 8 Ball says...</p>
                  </div>
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <p>{this.state.response}</p>
                  </div>
                </Typography>
              </div>
        </main>
    )
  }
}

export default App;

我的stats.js文件(我想最终输出统计信息):

import Header from '../components/Header.js'
import Link from 'next/link'
import { Component } from "react";
const moment = require('moment');
import { Chart } from "react-charts";
import Typography from '@material-ui/core/Typography';

class StatsPage extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      time: undefined
    };
    this.incrementCounter = this.incrementCounter.bind(this);
  }

  componentDidMount() {
    this.setState({
      count: parseInt(localStorage.getItem("count")) || 0
    });
  }

  incrementCounter() {
    const count = this.state.count + 1;
    localStorage.setItem("count", count);
    this.setState({
      count: count
    });
  }

  render() {
    return (
      <main>
        <Header />
          <h1>Game Statistics</h1>
            <Typography variant="title" color="inherit">
                <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                  <p>Total questions: {this.state.count}</p>
                </div>
                <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                  <p>Last question timestamp: {this.state.time}</p>
                </div>
              </Typography>
              <style jsx>{`
                h1 {
                  font-family:"Arial";
                  font-size:50px;
                }`}
              </style>
      </main>
    )
  }
}

export default StatsPage;

您在应用程序中设置状态,但随后再也不会使用它。 您在StatsPage中使用状态,但从未设置。 每个组件都有自己的状态,因此只选择一个您想要对此负责的组件,并在那里处理它。 如果您不确定要执行哪个组件,请在组件树中找到需要与时间交互的最高组件(设置或使用它),并将状态放在那里。 然后,它可以将其作为道具传递给所有关心它的孩子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM