React-从App重新加载外部组件

时间:2018-12-02 03:45:01

标签: javascript reactjs reload react-component

我还是React的新手。

我正在做一个猜谜游戏。页面加载时,所有内容均正确加载(至少在Chrome和Safari上)。猫按钮被分配了一个随机数,当单击它们时,它们会将相应的值发送到游戏逻辑。当达到或超过目标编号时,目标编号将重置。

这就是我想要的,但是我也希望按钮获得新的值。我希望Buttons组件重新加载并为按钮分配新值。我尝试使用以下https://reactjs.org/docs/react-component.html#updating中的更新方法。我不知道下一步该怎么做。

App.js

*LWin::
    Input, key, L1
    if (ErrorLevel = "NewInput")
        Send, {LWin}      ; LWin was pressed alone: pass-thru
    else if (IsLabel(key))
        Goto, % key
    else
        Send, % "#" key   ; pass-thru
return
*LWin UP::Input           ; stop listening for secondary key

; Tasks defined here
s:
    MsgBox, "s" task launched!
return
p:
    MsgBox, "p" task launched!
return

Buttons.js

import React, { Component } from 'react';
import './App.css';
import Buttons from "./components/Buttons/Buttons";

class App extends Component {

  targetNumber = (min, max) => {
    const targetNum = Math.floor(Math.random()*(max-min+1)+min);
    console.log(`Target number = ${targetNum}`);

    return targetNum
  };

  state = {
    targetNumber: this.targetNumber(19, 120),
    currentValue: 0,
    gamesWon: 0,
  };

  handleClick = (event) => {
      event.preventDefault();
      const currentValue = this.state.currentValue;
      const newValue = parseInt(event.target.getAttribute("value"));
        this.setState(
            {currentValue: currentValue + newValue}
        )
        // console.log(newValue);
    }

  componentDidUpdate() {
    if (this.state.currentValue === this.state.targetNumber) {
      this.setState(
          {
            targetNumber: this.targetNumber(19, 120),
            currentValue: 0,
            gamesWon: this.state.gamesWon + 1
          }
      )
    }
    else {
        if (this.state.currentValue >= this.state.targetNumber) {
            this.setState(
                {
                  targetNumber: this.targetNumber(19, 120),
                  currentValue: 0,
                  gamesWon: this.state.gamesWon,
                }
            );
        }
    }
  }

  render() {
    return (

      <div className="App">

        <img src={require("./images/frame.png")} alt="frame" id="instructFrame" />

        <div className="resultsDiv">

          <div className="targetNumber">
            Target number = {this.state.targetNumber}
          </div>

          <div className="currentValue">
              Current value = {this.state.currentValue}
          </div>

          <div className="gamesWon">
              Games won = {this.state.gamesWon}
          </div>

        </div>

        <div className="buttonGrid">
            <Buttons 
              onClick={this.handleClick} 
            />
        </div>

      </div>
    );
  }
}

export default App;

这是GitHub仓库。 https://github.com/irene-rojas/numberguess-react

1 个答案:

答案 0 :(得分:0)

您可以将key添加到链接到变量Button的{​​{1}}组件。这样,只要targetNumber发生变化,React就会重新呈现Button

targetNumber