Dit*_*ito 1 components split reactjs
我刚刚开始学习ReactJs,并且正在构建练习蛇游戏。
一切正常,但是我不喜欢我的“游戏”组件越来越大。我想不出将其拆分为几个更简单的组件的最佳方法
这是仓库,如果有任何更正和建议,我将不胜感激。
如果有多个操作作用于单个状态,则它们\xe2\x80\x99ll都需要放置在同一个组件中。状态改变的方式越多,组件就越大。如果一个组件的操作会影响多种类型的状态,那么该组件就会变得庞大。
\n\n这就是为什么你\xe2\x80\x99会想要在可能的情况下分解出更小的组件
\n\n这是关于如何分离组件的一个很好的例子?
\n\n实现此目的的更高级级别是代码分割。\n代码分割是 Webpack 和 Browserify(通过因子捆绑)等捆绑器支持的功能,它可以创建多个可以在运行时动态加载的捆绑包。
\n\n对应用程序进行代码分割可以帮助您\xe2\x80\x9clazy-load\xe2\x80\x9d 获取用户当前需要的内容,这可以显着提高应用程序的性能。虽然您没有减少应用程序中的代码总量,但您避免了加载用户可能永远不需要的代码,并减少了初始加载期间所需的代码量。
\n\nReact 文档在这里提供了非常简单的代码分割方法
\n小智 5
就我所看到的代码而言,您以正确的方式划分了组件,我认为,您不应进一步分解它们。
但是,您可以对Game.js文件进行一些更改:
您可以将函数分为utils文件(单独的.js文件),以更好地理解代码。
您可以将样式化的组件移动到Game.style.js之类的文件中
您也可以将挂钩用于方向状态。
以下是样式化组件的示例:
Game.js
import React from 'react'
import Board from './Board'
import Toolbar from './Toolbar'
// styles
import {Row, Wrapper} from './Game.style';
class Game extends React.Component {
constructor(props) {
}
initGame = () => {
}
updateCanvas = () => {
}
// for (let i = 0; i < snake.length; i++) {
// ctx.fillStyle = '#3682c9'
// ctx.fillRect(snake[i].x, snake[i].y, squareWidth, squareHeight)
// }
// ctx.fillStyle = '#a2d149'
// ctx.fillRect(0, 0, 20, 20)
// ctx.fillStyle = '#aad751'
// ctx.fillRect(20, 0, 20, 20)
// ctx.fillStyle = '#a2d149'
// ctx.fillRect(40, 0, 20, 20)
}
drawSnake = () => {
}
generateFood = () => {
}
drawFood = () => {
}
changeDirection = event => {
}
moveSnake = () => {
}
startGame = () => {
}
componentDidMount() {
this.refs.canvas.focus()
this.initGame()
}
componentDidUpdate() {}
render() {
const { boardWidth, boardHeight } = this.state
console.log(this.state)
return (
<Wrapper>
<Toolbar onClick={this.initGame} />
<canvas
ref="canvas"
onKeyDown={this.changeDirection}
tabIndex="0"
width={boardWidth}
height={boardHeight}
/>
</Wrapper>
)
}
}
export default GameRun Code Online (Sandbox Code Playgroud)
Game.style.js
import styled from 'styled-components'
export const Row = styled.div`
display: flex;
&:nth-child(odd) {
div:nth-child(even) {
background-color: #aad751;
}
}
&:nth-child(even) {
div:nth-child(odd) {
background-color: #aad751;
}
}
`;
export const Wrapper = styled.div`
display: flex;
flex-direction: column;
height: 100vh;
justify-content: center;
align-items: center;
`;Run Code Online (Sandbox Code Playgroud)
PS。我非常强调从其他utils文件中导入这些功能。
| 归档时间: |
|
| 查看次数: |
684 次 |
| 最近记录: |