如何将 Chessboard.js 与 Reactjs 一起使用?

2024-04-27

我一直在研究 chessboardjs (https://chessboardjs.com/ https://chessboardjs.com/)作为练习一些 React 编码的方法。但是,我无法获得仅在我的应用程序中显示板的简单示例。文档说要使用<div id="board" style={{width: 400}}/>在 HTML 中,以及var board = ChessBoard('board', 'start');开始。然而,ChessBoard('board', 'start');给我一个“对象不是函数”编译错误。我尝试过摆弄很多不同的事情(例如使用 jquery 标签添加匿名函数),但我似乎做错了一些事情。我希望有人能发现它。

我的 React 应用程序(使用打字稿)有标准的 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"
    }
   }

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

<Chessboard position="start"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 Chessboard.js 与 Reactjs 一起使用? 的相关文章

随机推荐