我正在尝试在 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.3
和 react 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/