我正在做关于井字游戏的反应教程。我决定创建辅助类方块,以存储 2D 游戏字段状态。
class Squares {
constructor(size) {
this._size = size
this._squares = Array(size * size).fill(null)
}
square(row, col, value) {
let position = (row - 1) * this._size + col - 1
if (value !== undefined)
this._squares[position] = value
return this._squares[position]
}
get size() {
return this._size
}
get copy() {
let squares = new Squares(this._size)
squares._squares = this._squares.slice()
return squares
}
}
并在组件的状态中使用它,就像这样。
class Game extends React.Component {
constructor() {
super()
this.state = {
history: [{
squares: new Squares(3)
}],
stepNumber: 0,
xIsNext: true,
}
}
但后来我得到了错误。"TypeError: Squares 不是构造函数">
组件内部的方块是未定义的!但是当我把我的类扭曲成函数时。
function Squares(size) {
class Squares {
...
}
return new Squares(size)
}
.. 组件类现在可以看到我的类!但是为什么?类和函数有什么区别?
类应该在使用之前定义它们,这是类和函数之间的区别之一。
虽然我测试了你的课程,当正方形低于游戏时它也可以工作。这可能是由于我的设置中发生了一些转译。