前言
- 最近看见个拖拽库叫react-dnd ,好像比较牛b,试用下玩玩。
文档
- https://react-dnd.github.io/react-dnd/ 这个地址比较墨迹,一般人访问不上。
- 大概简单看了下文档,文档的意思是,他们这个库是类似redux架构,而且分了Backends,item,monitor,Connectors等概念。反正尼玛看了就不想看的那种。
- 我这里直接记录下我的操作流程。
流程
- 首先使用cra初始化项目,为了更快的便于我理解这个库,所以使用ts制作。
- 先做个🐎:
import React from "react"; export default function Knight() {
return ( <span role="img" aria-label="horse"> 🐎 </span> ); }
讯享网
- 在app中渲染它
讯享网import React from "react"; import "./App.css"; import Knight from "./components/knight"; function App() {
return <Knight></Knight>; } export default App;
- 制作棋盘上的格子,黑白2色:
import React, {
PropsWithChildren } from "react"; interface SquareProps {
black: boolean; } export default function Square(props: PropsWithChildren<SquareProps>) {
const {
black, children } = props; const fill = black ? "black" : "white"; return ( <div style={
{
backgroundColor: fill, width: "100%", height: "100%", textAlign: "center", lineHeight: "62.5px", }} > {
children} </div> ); }
- 限定死棋盘大小500px
讯享网#root{
height:500px; width:500px; }
- 制作棋盘:
import React, {
useMemo } from "react"; import Square from "./square"; import Knight from "./knight"; function renderSquare( i: number, [knightX, knightY]: BoardProps["knightPosition"] ) {
const x = i % 8; const y = Math.floor(i / 8); const isKnightHere = x === knightX && y === knightY; const black = (x + y) % 2 === 1; const piece = isKnightHere ? <Knight /> : null; return ( <div key={
i} style={
{
width: "12.5%", height: "12.5%" }}> <Square black={
black}>{
piece}</Square> </div> ); } interface BoardProps {
knightPosition: [number, number]; } export default function Board(props: BoardProps) {
const {
knightPosition } = props; const squares = useMemo(() => {
let a = []; for (let i = 0; i < 64; i++) {
a.push(renderSquare(i, knightPosition)); } return a; }, [knightPosition]); return ( <div style={
{
width: "100%", height: "100%", display: "flex", flexWrap: "wrap", }} > {
squares} </div> ); }
- 渲染:
讯享网function App() {
return <Board knightPosition={
[1, 0]} />; }
- 这样,一个可以通过调整数组中数字来决定骑士位置的棋盘就做好了。
- 下面,我们需要使用数据驱动,点击棋盘上对应位置,然后🐎会自动跳过去。
- 同时使用规则来确定马是否可以跳那:
game.tsx
import {
BoardProps } from "./components/board"; export let knightPosition: BoardProps["knightPosition"] = [0, 0]; let observer: null | Function = null; function emitChange() {
if (observer) {
console.log(knightPosition); observer(knightPosition); } } export function observe(o: Function) {
observer = o; emitChange(); } export function moveKnight(toX: number, toY: number) {
knightPosition = [toX, toY]; emitChange(); } export function canMoveKnight(toX: number, toY: number) {
const [x, y] = knightPosition; const dx = toX - x; const dy = toY - y; return ( (Math.abs(dx) === 2 && Math.abs(dy) === 1) || (Math.abs(dx) === 1 && Math.abs(dy) === 2) ); }
app.tsx
讯享网import React, {
useState, useMemo } from "react"; import "./App.css"; import Board from "./components/board"; import {
knightPosition, observe } from "./game"; function App() {
const setState = useState(0)[1]; useMemo(() => {
observe(() => setState((st) => st + 1)); }, [setState]); return <Board knightPosition={
knightPosition} />; } export default App;
- 对棋盘添加点击事件:
import React, {
useMemo } from "react"; import Square from "./square"; import Knight from "./knight"; import {
moveKnight, canMoveKnight } from "../game"; function renderSquare( i: number, [knightX, knightY]: BoardProps["knightPosition"], handleSquareClick: Function ) {
const x = i % 8; const y = Math.floor(i / 8); const isKnightHere = x === knightX && y === knightY; const black = (x + y) % 2 === 1; const piece = isKnightHere ? <Knight /> : null; return ( <div onClick={
() => handleSquareClick(x, y)} key={
i} style={
{
width: "12.5%", height: "12.5%" }} > <Square black={
black}>{
piece}</Square> </div> ); } export interface BoardProps {
knightPosition: [number, number]; } export default function Board(props: BoardProps) {
const {
knightPosition } = props; function handleSquareClick(toX: number, toY: number) {
if (canMoveKnight(toX, toY)) {
moveKnight(toX, toY); } } const squares = useMemo(() => {
let a = []; for (let i = 0; i < 64; i++) {
a.push(renderSquare(i, knightPosition, handleSquareClick)); } return a; }, [knightPosition]); return ( <div style={
{
width: "100%", height: "100%", display: "flex", flexWrap: "wrap", }} > {
squares} </div> ); }
- 这样便完成了。试试如果点击可以让马正常跳即可。
- 到此为止,主角还没登场,就是react-dnd,下面进行安装:
讯享网yarn add react-dnd react-dnd-html5-backend
- 那个react-dnd-html5-backend就是他们所谓的后端的概念。因为还有个react-dnd-touch-backend,所以猜想是一个用的h5,一个用的touch。
- 先在board处导入它:
import {
DndProvider } from "react-dnd"; import {
HTML5Backend } from "react-dnd-html5-backend"; ...... ... export default function Board(props: BoardProps) {
...... return ( <DndProvider backend={
HTML5Backend}> ..... </DndProvider> ); }
- 这个dndprovider 应该就是利用context来传递信息的。
- 然后需要定义个拖动类型:
讯享网import React from "react"; import {
useDrag } from "react-dnd"; export const ItemTypes = {
KNIGHT: "knight", }; export default function Knight() {
const [x, drag] = useDrag({
item: {
type: ItemTypes.KNIGHT }, collect: (monitor) => ({
isDragging: !!monitor.isDragging(), }), }); return ( <span ref={
drag} role="img" aria-label="horse"> 🐎 </span> ); }
- 这个useDrag,返回3个属性:[CollectedProps, ConnectDragSource, ConnectDragPreview],这个看名字就知道是干啥的。
- 此时试着去拖一下🐎,发现已经可以拖动了,只是拖动后没放到位置上。
- 这个应该就是他拿了dom实例配置项加入dragging以及各种拖拽方法。
- item要写个type,这玩意是个常量,个人猜想是这样,因为拖拽时的那个api只能传url或者字符串,然后它需要一个唯一的字符串,来确定拖动到目标元素上收到的拖拽元素是谁,从而触发后续操作。
- 那个collect传递的monitor,试验了下,会在拖拽的几个事件中触发,不包括dragover,上面有些拖拽信息之类。根据文档解释,这个是传递state的,也就是第一个参数状态。
- 下面来处理drop。
- 新建个boardSquare利用useDrop来处理drop逻辑:
import React, {
PropsWithChildren } from "react"; import {
ItemTypes } from "./knight"; import {
useDrop } from "react-dnd"; import {
moveKnight } from "../game"; export default function BoardSquare({
x, y, children, }: PropsWithChildren<{
x: number; y: number }>) {
const [{
isOver }, drop] = useDrop({
accept: ItemTypes.KNIGHT, drop: () => moveKnight(x, y), collect: (mon) => ({
isOver: !!mon.isOver(), canDrop: !!mon.canDrop(), }), }); return ( <div ref={
drop} style={
{
position: "relative", width: "100%", height: "100%", }} > {
children} {
isOver && ( <div style={
{
position: "absolute", top: 0, left: 0, height: "100%", width: "100%", zIndex: 1, opacity: 0.5, backgroundColor: "yellow", }} /> )} </div> ); }
- board里面渲染包裹一层进行渲染:
讯享网function renderSquare( i: number, [knightX, knightY]: BoardProps["knightPosition"], handleSquareClick: Function ) {
const x = i % 8; const y = Math.floor(i / 8); const isKnightHere = x === knightX && y === knightY; const black = (x + y) % 2 === 1; const piece = isKnightHere ? <Knight /> : null; return ( <div onClick={
() => handleSquareClick(x, y)} key={
i} style={
{
width: "12.5%", height: "12.5%" }} > <BoardSquare x={
x} y={
y}> <Square black={
black}>{
piece}</Square> </BoardSquare> </div> ); }
- 这样在拖拽时放下,🐎会跑到相应格子上,同时拖拽中会有黄色方框显示落点。
- 下面要规定马的拖动位置,不能拖哪里就移动哪里,增加canDrop:
import React, {
PropsWithChildren } from "react"; import {
ItemTypes } from "./knight"; import {
useDrop } from "react-dnd"; import {
moveKnight, canMoveKnight } from "../game"; const Overlay = ({
color }: {
color: string }) => {
return ( <div style={
{
position: "absolute", top: 0, left: 0, height: "100%", width: "100%", zIndex: 1, opacity: 0.5, backgroundColor: color, }} /> ); }; export default function BoardSquare({
x, y, children, }: PropsWithChildren<{
x: number; y: number }>) {
const [{
isOver, canDrop }, drop] = useDrop({
accept: ItemTypes.KNIGHT, canDrop: () => canMoveKnight(x, y), drop: () => moveKnight(x, y), collect: (mon) => ({
isOver: !!mon.isOver(), canDrop: !!mon.canDrop(), }), }); return ( <div ref={
drop} style={
{
position: "relative", width: "100%", height: "100%", }} > {
children} {
isOver && !canDrop && <Overlay color="red" />} {
!isOver && canDrop && <Overlay color="yellow" />} {
isOver && canDrop && <Overlay color="green" />} </div> ); }
- 这样在拖到不能放的格子上,就会产生红色,拖到可以放的就是绿色,黄色就是可以放但是还没拖到的地方。并且,只有规定的发才可以拖放。
- 最后,换一个拖拽图片,这个换图片方法文档写的有点问题,经过我试验其实就是只要在旁边加个DragPreviewImage然后连起来就可以了:
讯享网export default function Knight() {
const [, drag, preview] = useDrag({
item: {
type: ItemTypes.KNIGHT }, collect: (monitor) => ({
isDragging: !!monitor.isDragging(), }), }); return ( <> <span ref={
drag} role="img" aria-label="horse"> <DragPreviewImage connect={
preview} src={
knightImage} ></DragPreviewImage> 🐎 </span> </> ); }
总结
- 初次使用,猜想是react-dnd将数据流直接打通,用redux方式进行传递拖拽数据,同时分离除了h5还有touch的backend,使得h5拖拽和移动端拖拽实现变得更为容易。
- 最后,需要代码自取https://github.com/yehuozhili/react-dnd-demo

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/99108.html