react 开发入门

本文介绍了React开发的基础环境配置,包括如何安装React、创建本地服务器及启动运行。接着详细讲解了如何从零开始实现一个三子棋游戏,包括初始化设置、增加交互功能,并给出了源码地址,帮助初学者快速入门React开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


环境配置

安装react

  直接通过命令安装:npm install -g create-react-app
  

创建本地服务器

  直接通过命令安装:create-react-app first-demo(first-demo为app名称)
  

启动运行

  直接通过命令安装:
   cd first-demo
   npm start
  

修改测试

  按照提示修改程序app.js文件,修改后页面会自动刷新
  

三子棋游戏

初始化
  1. 删除src目录下所有文件
  2. 复制https://github.com/zacSuo/react-demo/archive/1.0.zip中的index.css和index.js文件
  3. 启动查看npm start
    在这里插入图片描述
增加交互

使用数组将历史数据存储在最上层的game中,可以访问历史步骤,代码如下:

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

function Square(props){
    return (
      <button className="square" onClick={props.onClick}>
        {props.value}
      </button>
    );
}

function calculateWinner(squares){
    const lines = [    
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
    ];
    for (let i=0;i<lines.length;i++){
        const [a,b,c] = lines[i];
        if(squares[a] && squares[a] == squares[b] && squares[a] == squares[c])
        {
            return squares[a];
        }
    }
    return null;
}

function getStrByNext(flag){
    return flag?'X':'O';
  }

class Board extends React.Component {

  renderSquare(i) {
    return (
        <Square 
            value={this.props.squares[i]}
            onClick = {() => this.props.onClick(i)}
        />
    );
  }

  render() {
    return (
      <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 {
  constructor(){
    super();
    this.state = {
        history:[{
            squares:Array(9).fill(null),
        }],
        xIsNext:true,
        currentIdx:0,
    };
  }

  handleClick(i){
    const history = this.state.history;
    const squares = history[this.state.currentIdx].squares.slice();
    const lastSquares = history[history.length - 1].squares;
    if(calculateWinner(lastSquares) || lastSquares[i]){
        return;
    }
    squares[i] = getStrByNext(this.state.xIsNext);
    this.setState({
        history:history.concat([{
                squares:squares
            }]),
        xIsNext: !this.state.xIsNext,
        currentIdx: this.state.currentIdx + 1,
    });
  }

  jumpTo(step){
    this.setState({
        currentIdx:step,
        xIsNext:(step % 2)?false:true,
    })
  }

  render() {
    const history = this.state.history
    const squares = history[this.state.currentIdx].squares;
    const winner = calculateWinner(squares);

    const moves = history.map((step,move) =>{
        const desc = move?'Move #'+move:'Game Start';
        return(
            <li key={move}>
                <a href="#" onClick={() => this.jumpTo(move)} >{desc}</a>
            </li>
        )
    })

    let status;
    if(winner){
        status = 'Winner: ' + winner;
    }else{
        status = 'Next player: ' + getStrByNext(this.state.xIsNext);
    }
    return (
      <div className="game">
        <div className="game-board">
          <Board 
            squares={squares}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{ status}</div>
          <ol>{ moves}</ol>
        </div>
      </div>
    );
  }
}

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

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

最终效果

在这里插入图片描述

源码地址

https://github.com/zacSuo/react-demo/releases/tag/2.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

具身小站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值