javascript - 为什么我的变量在反应的构造函数之外未定义?
问题描述
我正在尝试将我的图标的 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 = [...]
您所缺少的。
推荐阅读
- javascript - 双仪表板谷歌图表
- angular - 我有 npm 包的 repo 叉子。我应该如何使用它?
- authentication - 针对 Active Directory 的身份验证.. DirectorySearcher 的必要性
- c# - Filling a constructor with a loop
- python - 解决时scipy长时间停顿
- javascript - 在打字稿中解析 JSON 数组
- javascript - 错误:未捕获的异常:编译错误:
- php - 奏鸣曲 没有可用于当前请求的网站
- javascript - 如何在 JavaScript 中动态创建高阶函数?
- cpanel - PCI 扫描仪显示对端口 2078 和 2080 的 TLSv1 支持