[英]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.