首页 > 解决方案 > 当组件变大时如何拆分组件。ReactJs 或 React Native

问题描述

我刚刚开始学习 ReactJs,并且正在构建蛇游戏以进行练习。

一切正常,但我不喜欢的是我的“游戏”组件越来越大。我想不出将它分成几个更简单的组件的最佳方法

这是回购协议,我将不胜感激任何更正和建议。

标签: reactjsreact-nativesplitcomponents

解决方案


就我所看到的代码而言,您以正确的方式划分了组件,在我看来,您不应该进一步分解它们。

但是,您可以对 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 文件中导入这些函数。


推荐阅读