首页 > 解决方案 > ReactJS useGesture:类型错误集不是函数

问题描述

我一直在尝试从useGesture 文档中获取示例

但是无论我尝试什么,我都会不断收到typeerror set is not a function error

import './App.css';
import React, {useState} from "react"
import { useSpring, animated } from "react-spring"
import { useDrag } from "react-use-gesture"
import data from './data';

function App() {
  const [{ x, y }, set] = useSpring(() => ({ x: 0, y: 0 }))

  // Set the drag hook and define component movement based on gesture data
  const bind = useDrag(({ down, movement: [mx, my] }) => {
    set({ x: down ? mx : 0, y: down ? my : 0 })
  })

  // Bind it to a component
  return <animated.div {...bind()} style={{ x, y }} className="box"/>
}

export default App;

我的版本是最新的

{
  "name": "gesture-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.10",
    "@testing-library/react": "^11.2.6",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "react-spring": "^9.0.0",
    "react-use-gesture": "^9.1.3",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我尝试了许多不同的版本,但总是收到此错误。有任何想法吗?

标签: reactjsreact-spring

解决方案


我今天也遇到了这个问题。显然,useSpring now(今天安装)的第二个返回值返回“弹簧对象”。尝试

function App() {
    const [{ x, y }, spring] = useSpring(() => ({ x: 0, y: 0 }));

    // Set the drag hook and define component movement based on gesture data
    const bind = useDrag(({ down, movement: [mx, my] }) => {
        spring.set({ x: down ? mx : 0, y: down ? my : 0 });
    });

    // Bind it to a component
    return <animated.div {...bind()} style={{ x, y }} className="box" />;
}

依赖项是

"react-spring": "^9.0.0",
"react-use-gesture": "^9.1.3",

这可能没有多大帮助,随着向 9.0.0 的过渡,还有更多尚未在文档中找到的更改。我的建议是转到示例并检查沙箱以获取有效的版本组合。


推荐阅读