首页 > 解决方案 > 为什么我的变量在反应的构造函数之外未定义?

问题描述

我正在尝试将我的图标的 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是未定义的。我现在该怎么办?

标签: javascriptreactjs

解决方案


在您的构造函数中更改var classList = [...]this.classList = [...]您所缺少的。


推荐阅读