我试图在ReactJS教程井字游戏中完成额外的练习。
现在我有了这段代码:
class Board extends React.Component { renderSquare(i) { return ( <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} /> ); } render() { return ( <div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); }
}
{this.renderSquare(x)}我不想用9次硬编码,而是想用两个循环替换它们或使用它们,map(map())但是我写的所有内容都比硬编码差。
{this.renderSquare(x)}
map(map())
有没有更好的方法可以避免硬编码?
使用循环可能会更好的主要原因是因为循环更通用。
这里有一些建议:
您可以在两个变量中保留行数和每行的平方数,这些变量可以作为循环限制,然后调整网格仅需要更新这两个变量。
将代码拆分为几种方法也可能会对其进行清理。
这是一个带有循环的示例:
// these can also be passed in as `props` // if you want to use them like `<Board totalRows={3} squaresPerRow={3} squares={...}/>` const totalRows = 3; const squaresPerRow = 3; class Board extends React.Component { renderSquare(i) { // ... } renderRow(row) { const squares = []; const offset = row * squaresPerRow; // this makes sure first row is 0,1,2, second row is 3,4,5, etc. for (let s = 0; s < squaresPerRow; s++) { squares.push( this.renderSquare(offset + s); ); } return ( <div className="board-row"> {squares} </div> ) } render() { const rows = []; for (let r = 0; r < totalRows; r++) { rows.push( this.renderRow(r) ); } return <div>{rows}</div>; } }