javascript - useRef() 无效 Hook 调用 [NextJs]

标签 javascript reactjs react-hooks next.js use-ref

我正在尝试在 NextJs 项目中的函数组件主体内使用 useRef() Hook ,但仍然出现以下错误。我已经完成了 React Hook 规则,但我找不到这个错误的原因并且这不起作用。 有人有想法吗?

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

import  React, { useRef } from 'react';

export default function Diagram() {

  const svgRef = useRef();

  return (
      <>
        <div className="container-svg py-4">
        <svg  ref={svgRef} viewBox="0 0 300 300">
        <g transform="translate(150, 150)">
          <g>
            <path id="triangle" d="M0, -125 L-150,150 L150, 150 L0, -125 M 0,50 L-150, 150 M150, 150 L0,50  L0,-125" stroke="black" fill="none"/>
          </g>
            {
              posts.map( post => {
                return (
                  <circle key={post.id} className="circle" cx={post.point.x} cy={post.point.y} r="5" />
                )
              })
            }
            <circle className="circle" cx="0" cy="0" r="5" />
          </g>
        </svg>
      </div>
      </>
  )
}

最佳答案

我正在使用 next 10.1.3react 17.0.1 我使用了 React.createRef() 因为 useRef( ) 不工作。我根据最初提出的问题做了一个例子。我添加这个是因为评论中的 createRef 答案不完整,这很容易理解。

import  React from 'react';

export default function Diagram() {

  const svgRef = React.createRef();

  return (
      <>
        <div className="container-svg py-4">
        <svg  ref={svgRef} viewBox="0 0 300 300">

...

关于javascript - useRef() 无效 Hook 调用 [NextJs],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63652894/

相关文章:

javascript - React-Bootstrap Modal 表单入口

javascript - 使用 jQuery Mobile 加载 Google Charts

javascript - 无法使用 AngularJS 访问 JSON 对象

javascript - Material UI SelectField 组件与状态不同步(使用 React/Redux)

reactjs - 如何让Query在组件onmount时执行,并在稍后由用户事件触发?

javascript - 在不广播 Clients.All.someMethod() 和炸毁客户端资源的情况下确定 Signal R 连接状态

javascript - localStorage 值不会自动更新

javascript - react : Flow: Import a local js file - cannot resolve issue module

reactjs - 当使用 useState 钩子(Hook)更改 props 时,组件不会重新渲染

javascript - React+gsap 使用随机动画元素组完成后无法工作?