我正在做关于 Tic Tac Toe 游戏的 React 教程。我决定创建辅助类 Squares,以存储 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,
}
}
但后来我得到了错误。“类型错误:Squares 不是构造函数”
内部组件 Squares 未定义!但是当我把我的班级变成功能时。
function Squares(size) {
class Squares {
...
}
return new Squares(size)
}
.. 组件类现在可以看到我的类了!但为什么?类和函数有什么区别?
类应该在使用之前定义,这是类和函数之间的区别之一。
尽管我测试了您的课程,但当 Squares 低于 Game 时它也有效。这可能是由于我的设置中发生了一些转译。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句