簡體   English   中英

為什么我的變量在反應的構造函數之外未定義?

[英]why is my variable is undefined outside of a constructor on react?

我正在嘗試將我的圖標的 classList 設置為數組中的隨機值。 但是當我運行這段代碼時,它說“this.classList”是未定義的。 為什么會這樣?

這是我的完整文件,我在我的主 html 文件中插入了 fontawsome 文件。

 //Heres the Dice.js file: import React, { Component } from "react"; import "./Dice.css"; class Dice extends Component { constructor(props) { super(props); this.state = { class: [] }; var classList = [ "fas fa-dice-one dice", "fas fa-dice-two dice", "fas fa-dice-three dice", "fas fa-dice-four dice" ]; let numPicker = this.numPicker.bind(this); } numPicker(e) { let randNum = Math.floor(Math.random() * this.classList.length); //Why is this.classList is Undefined let classPicker = this.classList[randNum]; this.state.class.push(classPicker); } render() { return ( <div> {this.numPicker()} <i className={this.state.class}></i> <button onClick={this.diceChanger()}>Click Me</button> </div> ); } } export default Dice; //Heres the Default App.js file: import React from "react"; // import logo from './logo.svg'; import "./App.css"; import Dice from "./Dice"; function App() { return ( <div className="App"> <Dice /> </div> ); } export default App;
 .dice { font-size: 120px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

我運行它,它說this.classList是未定義的。 我現在該怎么辦?

在您的構造函數var classList = [...]更改為this.classList = [...]這就是您所缺少的。

將數組添加到 function 不是更有意義嗎? 我建議閱讀/遵循更多指南。 例如,您應該使用 setState 而不是您正在嘗試做的事情。

代碼示例:

class Dice extends Component {
  constructor(props) {
    super(props);
    this.state = { currentClass: [] };
  }

  numPicker(e) {
    const classList = [
      "fas fa-dice-one dice",
      "fas fa-dice-two dice",
      "fas fa-dice-three dice",
      "fas fa-dice-four dice"
    ];
    const randNum = Math.floor(Math.random() * classList.length);
    const currentClass = this.classList[randNum];
    this.setState({ currentClass });
  }

  render() {
    return (
      <div>
        {this.numPicker()}
        <i className={this.state.currentClass}></i>
        <button onClick={this.diceChanger()}>Click Me</button>
      </div>
    );
  }
}

export default Dice;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM