gpt4 book ai didi

javascript - 使用组件以外的 es6 类(React Js)

转载 作者:行者123 更新时间:2023-11-30 21:20:19 25 4
gpt4 key购买 nike

在React官方tutorial (井字游戏),使用了三个组件:GameBoardSquare

游戏包含一个 squares 数组,其中可以包含 X、O 和 null:这三个都是原始类型。

我的问题:使用 es6 类(不扩展组件,因为不渲染任何东西)来保存信息基元是否是一种公认的做法?当然不能保存?这些类也可以从其他类继承。

例如,我们能否将 Piece 类的对象存储在 squares 数组中,而不是 X/O 在正方形中显示 piece.name ?我们能否将 piecei 移动到 j 以将其反射(reflect)在方 block 板上?

需要问这个有两个原因:

  1. 几乎所有 React 示例都围绕组件展开。我还没有看到其他用途的类。

  2. 不鼓励组件 ( composition vs inheritance ) 继承,我认为在上面的示例中特化 Piece 类需要继承。

谢谢。

最佳答案

这是我正在谈论的例子。我没有包含任何状态更新机制,这是相当概念性的,但我认为您会明白要点。

// holds the state of your board and calculates the view layer
class Board extends PureComponent {
constructor( props ) {
super( props );

// create pieces for however you want the game to start
this.pieces = {
p1: new piece( "Lumberjack" ),
p2: new piece( "Lumberjack" ),
p3: new piece( "Lumberjack" ),
p4: new piece( "Tree" ),
p5: new piece( "Tree" ),
p6: new piece( "Tree" )
}

// flatten for easy and speed of access
const { p1, p2, p3, p4, p5, p6 } = this.pieces;

// initial state, this is what gets updated by this.setState method
// to update the rendered view
this.state ={
squares: [
[ p1, p2, p3 ],
[ null, null, null ],
[ p4, p5, p6 ]
]
};
}

// render method that produces the view
render() {
const { squares } = this.state;
const iLength = squares.length;
let i, j jLength, components = [ ];

// generate the Squares from this.state data
for ( i = 0; i < iLength; i++ ) {
jLength = squares[ i ].length;
for ( j = 0; jLength; j++ ) {
components.push( <Square piece={ squares[ i ][ j ] } /> );
}
}

// render the Squares containing the pieces
return (
<div className="board">
{ components }
</div>
);
}
}

// piece constructor
function piece( name ) {
this.name = name;
}

您最终会在棋盘上有 9 个方 block 。一侧是 Lumberjacks,中间是空的,另一侧是非常害怕的 Tree's。

关于javascript - 使用组件以外的 es6 类(React Js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com