【问题标题】:Looking to output timestamp to component for React Button onClick event希望为 React Button onClick 事件输出时间戳到组件
【发布时间】:2019-03-15 18:20:45
【问题描述】:

我还在学习 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;

【问题讨论】:

    标签: javascript html node.js reactjs


    【解决方案1】:

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

    【讨论】:

    • 好的,谢谢 - 我已经更改了每个组件的状态,因此仅存在相关状态。您对我如何让 state.time 在 statistics.js 中显示有任何想法吗?
    • 如果时间是父组件的状态,那么您可以让该父组件将时间作为道具传递给 StatsPage。然后 StatsPage 将使用this.props.time。如果您可以向我们展示您在哪里呈现 StatsPage,也许我可以更具体。
    猜你喜欢
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    相关资源
    最近更新 更多