reactjs - 当组件变大时如何拆分组件。ReactJs 或 React Native
问题描述
我刚刚开始学习 ReactJs,并且正在构建蛇游戏以进行练习。
一切正常,但我不喜欢的是我的“游戏”组件越来越大。我想不出将它分成几个更简单的组件的最佳方法
这是回购协议,我将不胜感激任何更正和建议。
解决方案
就我所看到的代码而言,您以正确的方式划分了组件,在我看来,您不应该进一步分解它们。
但是,您可以对 Game.js 文件进行一些更改:
您可以将您的函数分成 utils 文件(一个单独的 .js 文件),以便更好地理解您的代码。
您可以将样式化的组件移动到 Game.style.js 之类的文件中
您也可以使用钩子来获取方向状态。
下面给出了样式组件的示例:
游戏.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
游戏风格.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 文件中导入这些函数。
推荐阅读
- android - Android Kotlin - 对话框片段错误(不能使用提供的参数调用以下函数)
- unicode - 如何使用 senthamizh 字体 SMZTH(泰米尔语)?
- html - 响应式页脚不停留在页面底部
- android - 如何通过 GSON / Retrofit 获得价值?
- sql - Postgresql WHERE 与 age() 函数
- python - 删除 Sublime Text 红色弹出窗口
- java - Spring Data JPA 将嵌套集合大小限制为 Pageable
- android - 带 GSM 模块的 DIY Raspberry pi 安卓手机?
- php - 用于测试的 PHP XMLWriter 输出格式
- javascript - querySelectorAll 请求中的错误“对象引用链太长”