【发布时间】:2019-08-04 23:39:57
【问题描述】:
我刚刚开始学习 ReactJs,我正在构建贪吃蛇游戏以供练习。
一切正常,但我不喜欢的是我的“游戏”组件越来越大。我想不出将它分成几个更简单的组件的最佳方法
这里是repo,如有任何更正和建议,我将不胜感激。
【问题讨论】:
标签: reactjs react-native split components
我刚刚开始学习 ReactJs,我正在构建贪吃蛇游戏以供练习。
一切正常,但我不喜欢的是我的“游戏”组件越来越大。我想不出将它分成几个更简单的组件的最佳方法
这里是repo,如有任何更正和建议,我将不胜感激。
【问题讨论】:
标签: reactjs react-native split components
就我所看到的您的代码而言,您以正确的方式划分组件,在我看来,您不应该进一步分解它们。
但是,您可以对 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 Game
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;
`;
PS。我非常强调从另一个 utils 文件中导入这些函数。
【讨论】:
如果有多个动作作用于一个状态,它们都需要放在同一个组件中。状态改变的方式越多,组件就越大。如果一个组件有影响多种状态的动作,这个组件就会变得庞大。
这就是为什么您要尽可能地分解出较小的组件
这是How do you separate components?上的一个很好的例子
实现此目的的更高级级别是代码拆分。 Code-Splitting 是 Webpack 和 Browserify 等打包工具支持的一项功能(通过 factor-bundle),它可以创建多个可以在运行时动态加载的包。
对您的应用进行代码拆分可以帮助您“延迟加载”用户当前需要的内容,从而显着提高应用的性能。虽然您没有减少应用中的总代码量,但您避免了加载用户可能永远不需要的代码,并减少了初始加载期间所需的代码量。
React 文档提供了非常简单的代码拆分方式here
【讨论】:
如果您想在 React Native
中将组件拆分为子组件那么你就可以使用这个VS Code Extension
【讨论】: