如何在 Reactjs 中使用 Chessboard.js?

How to use Chessboard.js with Reactjs?

我一直在研究 chessboardjs (https://chessboardjs.com/),以此来练习一些 React 编码。但是,我无法获得仅在我的应用程序中显示电路板的简单示例。文档说在 HTML 中使用 <div id="board" style={{width: 400}}/>,然后使用 var board = ChessBoard('board', 'start'); 开始。但是,ChessBoard('board', 'start'); 给我一个 "object not a function" 编译错误。我试过很多不同的东西(比如用 jquery 标签添加匿名函数),但我似乎做错了什么。希望有人能发现。

我的 React 应用程序(使用 typescript)有标准的 App 组件,它只有一个 ChessComponent,看起来如下:

import * as React from 'react';
import {ChessBoard} from 'chessboardjs';
import * as $ from 'jquery';

class ChessComponent extends React.Component {
    constructor(props:any) {
        super(props);
    }

    componentDidMount() {
        $(function() {
            var board = ChessBoard('board', 'start');
        });
    }

    render() {
        return (
            <div id="board" style={{width: 400}}/>
        )
    }
}

export default ChessComponent

我的 package.json 看起来像这样:

  {
    "name": "chess-app",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
      "chess": "^0.4.1",
      "chessboardjs": "0.0.1",
      "jquery": "^3.4.0",
      "react": "^16.5.2",
      "react-bootstrap": "^0.32.4",
      "react-dom": "^16.5.2",
      "react-scripts-ts": "3.1.0",
      "tslint": "^5.11.0",
      "tslint-react": "^3.6.0"
    },
    "scripts": {
      "start": "react-scripts-ts start --noUnusedParameters=false",
      "build": "react-scripts-ts build",
      "test": "react-scripts-ts test --env=jsdom",
      "eject": "react-scripts-ts eject"
    },
    "devDependencies": {
      "@types/chessboardjs": "^0.3.1",
      "@types/jest": "^23.3.2",
      "@types/jquery": "^3.3.29",
      "@types/node": "^10.11.3",
      "@types/react": "^16.4.14",
      "@types/react-dom": "^16.0.8",
      "typescript": "^3.1.1"
    }
   }

以防其他人遇到类似问题,我想我会回到这个问题并回答我自己的问题。

一个技巧是将必要的脚本添加到 index.html:

<script src="https://code.jquery.com/jquery-2.1.4.js"></script> <script src="https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.js" integrity="sha384-8Vi8VHwn3vjQ9eUHUxex3JSN/NFqUg3QbPyX8kWyb93+8AC/pPWTzj+nHtbC5bxD" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.css" integrity="sha384-q94+BZtLrkL1/ohfjR8c6L+A6qzNH9R2hBLwyoAfu3i/WCvQjzL2RQJ3uNHDISdU" crossorigin="anonymous">

这样,jquery 和 chessboardjs 功能都可以在 window 对象上使用。现在你可以调用 window.Chessboard 来制作电路板(需要一些设置)。

使用 reactjs-typescript 的 chessboardjs 快速 n-dirty 设置可能如下所示:


import React from 'react';
import './App.css';

// This is a bit of a hack to declare jquery on the window object. It also makes it possible to call window.chessBoard further below
declare var window : any; 
window.$ = window.jQuery = $;

export default class App extends React.Component {

  // Please disregard the massive overuse of the any type here
  private boardRef: any;
  private chessBoard: any;
  private boardId: string;
  private defaultConfig: any;

  constructor(props: any) {
    super(props);
    this.boardRef = React.createRef();
    this.boardId = "board1";
    const themePath = process.env.PUBLIC_URL + '/assets/img/chesspieces/wikipedia/{piece}.png'

    this.defaultConfig = {
      appearSpeed: 25,
      draggable: true,
      dropOffBoard: 'snapback',
      moveSpeed: 25,
      orientation: 'white',
      position: 'start',
      showErrors: 'console',
      showNotation: true,
      snapSpeed: 25,
      snapbackSpeed: 50,
      pieceTheme: themePath,
      sparePieces: false,
      trashSpeed: 25,
    };
  }


  componentDidMount() {
    if (window && !window.ChessBoard) return
    if (window && !window.$) return

    this.chessBoard = window.ChessBoard(this.boardId, this.defaultConfig);
  }

  componentWillUnmount() {
    this.chessBoard.destroy();
  }

  render() {
    return (
      <div className="App">
        <div id={this.boardId} style={{width: "400px"}} ref={this.boardRef}></div>
      </div>
      ); 
    } 
  }

但是,如果您正在考虑将 Chessboard.js 与 React 结合使用,我建议您看看 Simon Ansells React-ChessboardJs-Wrapper:https://github.com/ginger-gm/react-chessboardjs-wrapper

这也使得向您的看板添加促销对话变得容易。

如果您正处于将 React 与其他库集成的类似困境中,我还建议您阅读他们关于该主题的文档,我最初以某种方式错过了它:

如果你想用 reactjs 构建一个棋盘,我会说 chessboardjsx 是正确的选择。它为您提供了一个棋盘组件,您可以在其中传递不同的道具来自定义棋盘。以下是示例开始位置:

<Chessboard position="start"/>