【发布时间】:2017-06-16 17:09:04
【问题描述】:
我正在做关于井字游戏的 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,
}
}
但后来我得到了错误。 “TypeError: Squares 不是构造函数”
内部组件 Squares 未定义!但是当我把我的类变成函数时。
function Squares(size) {
class Squares {
...
}
return new Squares(size)
}
.. 组件类现在可以看到我的类了! 但为什么?类和函数有什么区别?
【问题讨论】:
-
这对我来说似乎工作正常:codepen.io/anon/pen/MoJYoO?editors=1011
-
是的。我在我的项目中进行了测试并且工作正常。 Game 和 Squares 是否在同一个文件中?
-
问题已解决。助手类在组件类之后,这就是它不能正常工作的原因。 @croraf 的回答绝对正确。
-
让我感到困惑的是,在我的设置中,我在 Game 下面有 Squares,它仍然有效。可能是因为我使用 webpack 和 babel 转译。但是当我在 Squares 上面添加“var a = Squares(1)”时,我得到了和你一样的错误。
标签: javascript reactjs