You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React无JSX开发井字棋:点击单元格添加X的实现方法

Hey there! I totally get how tricky it can be to wrap your head around vanilla React (no JSX) when you're used to the more concise JSX syntax. Let's walk through exactly how to implement the click-to-add-'X' functionality for your tic-tac-toe game step by step.

Core Concepts to Remember

First, without JSX, we rely entirely on React.createElement() to build our UI. We also need to manage state to track which cells have been clicked (since React is state-driven). Here's a complete, working implementation:

import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function TicTacToe() {
  // Initialize state: an array of 9 empty strings (one for each cell in 3x3 grid)
  const [board, setBoard] = useState(Array(9).fill(''));

  // Handle cell click: update state only if the cell is empty
  const handleCellClick = (index) => {
    // Ignore clicks on already filled cells
    if (board[index] !== '') return;

    // Create a copy of the board array (never mutate state directly!)
    const updatedBoard = [...board];
    updatedBoard[index] = 'X';
    setBoard(updatedBoard);
  };

  // Helper to create a single cell component
  const buildCell = (index) => {
    return React.createElement(
      'button',
      {
        className: 'tic-tac-toe-cell',
        onClick: () => handleCellClick(index),
        style: {
          width: '75px',
          height: '75px',
          fontSize: '2.5rem',
          border: '1px solid #ddd',
          cursor: 'pointer',
          backgroundColor: board[index] ? '#f0f0f0' : 'white'
        }
      },
      board[index] // Display 'X' if the cell is filled, empty otherwise
    );
  };

  // Helper to build the 3x3 grid
  const buildBoard = () => {
    const boardRows = [];
    for (let row = 0; row < 3; row++) {
      const rowCells = [];
      for (let col = 0; col < 3; col++) {
        const cellIndex = row * 3 + col;
        rowCells.push(buildCell(cellIndex));
      }
      // Create a row div to hold 3 cells
      boardRows.push(
        React.createElement(
          'div',
          { style: { display: 'flex' } },
          ...rowCells
        )
      );
    }
    return boardRows;
  };

  // Render the full game UI
  return React.createElement(
    'div',
    { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: '3rem' } },
    React.createElement('h2', null, 'Vanilla React Tic-Tac-Toe'),
    React.createElement('div', null, ...buildBoard())
  );
}

// Mount the app to the DOM
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(TicTacToe));

Key Breakdown of the Code

  1. State Management: We use useState to create a board state variable—an array of 9 empty strings. Each index corresponds to a cell in the 3x3 grid (e.g., index 0 is top-left, index 8 is bottom-right).
  2. Click Handler: handleCellClick checks if the target cell is empty. If it is, we create a copy of the board array (critical to avoid mutating state directly), set the clicked index to 'X', and update the state with setBoard.
  3. Cell Component: buildCell uses React.createElement to create a button for each cell. We pass the click handler, style, and the current cell value (from state) as props/content.
  4. Grid Construction: buildBoard loops to create 3 rows, each containing 3 cells. We use flexbox styling to arrange the cells into a grid.

How to Test This

Just drop this code into your React project (make sure you have React and ReactDOM installed), and add a <div id="root"></div> to your HTML file. When you click any empty cell, it will display 'X'—and already filled cells won't respond to clicks.

内容的提问来源于stack exchange,提问作者Chris Nielsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:01:21