React--安装篇

78 阅读1分钟

由于工作需要,开始学习react框架,之前对于react了解不是特别多,所以先从react的官方文档一步一步学习, 首先跟着文档做个简单的小游戏-- 井字棋

前提准备

Node >= 14.0.0 和 npm >= 5.6

配置开发环境

npx create-react-app my-app
cd my-app
npm start

在 src/ 文件夹中创建一个名为 index.css 的文件,并拷贝

body {
  font: 14px "Century Gothic", Futura, sans-serif;
  margin: 20px;
}

ol, ul {
  padding-left: 30px;
}

.board-row:after {
  clear: both;
  content: "";
  display: table;
}

.status {
  margin-bottom: 10px;
}

.square {
  background: #fff;
  border: 1px solid #999;
  float: left;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 34px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 34px;
}

.square:focus {
  outline: none;
}

.kbd-navigation .square:focus {
  background: #ddd;
}

.game {
  display: flex;
  flex-direction: row;
}

.game-info {
  margin-left: 20px;
}

在 src/ 文件夹下创建一个名为 index.js 的文件,并拷贝

class Square extends React.Component {
  render() {
    return (
      <button className="square">
        {/* TODO */}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square />;
  }

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</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>
    );
  }
}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

// ========================================

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Game />);

拷贝以下三行代码到 src/ 文件夹下的 index.js 文件的顶部:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

项目文件夹执行npm start 在浏览器访问 http://localhost:3000就可以在浏览器中看见一个空的井字棋的棋盘了 至此,已经搭建好了一个react项目,可以更改index.js / index.css等文件来实现你的项目