首页 > 解决方案 > 如何在 React 中使用变量?

问题描述

我想在网页的开头从用户那里获得关于他/她的名字的输入,并将其显示在屏幕上。我创建了一个 let 变量,componentDidMount但它一次又一次地无限询问。在其他方法中,它说fullname的是undefined. 正确的做法是什么?

import './App.css';
import React, { Component } from 'react';
import Clock from './Clock';

class App extends Component {
  state = {
    secondRatio: 0,
    minuteRatio: 0,
    hourRatio: 0
  }

  getName() {
    let fullname = prompt("Lutfen isim giriniz:");
    return fullname;
  }

  componentDidMount() {
    setInterval(() => (
      this.setClock()
    ), 1000);
    console.log(this.fullname);
  }

  setClock = () => {
    const currentDate = new Date;
    let secondRatio = currentDate.getSeconds() / 60;
    let minuteRatio = (secondRatio + currentDate.getMinutes()) / 60;
    let hourRatio = (minuteRatio + currentDate.getHours()) / 12;
    this.setState({ secondRatio: secondRatio });
    this.setState({ minuteRatio: minuteRatio });
    this.setState({ hourRatio: hourRatio });
  }

  render() {
    const { secondRatio, minuteRatio, hourRatio } = this.state;

    return (
      <fragment>
        <div>  <h1 className="text1">Hello, {this.getName().fullname} ! Welcome! </h1>
          <div className="test"><Clock secondRatio={secondRatio} minuteRatio={minuteRatio} hourRatio={hourRatio} />
          </div>
        </div>
      </fragment>
    );
  }
}

export default App;

标签: javascriptreactjs

解决方案


你的班级没有fullname财产,所以this.fullname总是如此undefinedfullname它与方法中使用的变量无关getName

您可以做的是fullname在您的类中创建一个属性并将提示的值分配给该属性componentDidMount

class App extends Component {
  fullname = undefined;

  state = {
    secondRatio: 0,
    minuteRatio: 0,
    hourRatio: 0
  };

  getName() {
    this.fullname = prompt("Lutfen isim giriniz:");
  }

  componentDidMount() {
    this.getName();
    setInterval(() => (
      this.setClock()
    ), 1000);
  }

  setClock = () => {
    const currentDate = new Date;
    let secondRatio = currentDate.getSeconds() / 60;
    let minuteRatio = (secondRatio + currentDate.getMinutes()) / 60;
    let hourRatio = (minuteRatio + currentDate.getHours()) / 12;
    this.setState({ secondRatio: secondRatio });
    this.setState({ minuteRatio: minuteRatio });
    this.setState({ hourRatio: hourRatio });
  };

  render() {
    const { secondRatio, minuteRatio, hourRatio } = this.state;

    return (
      <fragment>
        <div>  <h1 className="text1">Hello, {this.fullname} ! Welcome! </h1>
          <div className="test"><Clock secondRatio={secondRatio} minuteRatio={minuteRatio} hourRatio={hourRatio} />
          </div>
        </div>
      </fragment>
    );
  }
}

推荐阅读