useRef()
和我正在使用
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.createRef()
不起作用。我以最初提出的问题为例。我添加了这一点,因为评论中的createref答案是不完整的,这使得很容易理解。
useRef()
这可能是因为useref()和其他React挂钩是客户端组件独有的。如果您不指定组件是客户端,则NextJS的后期版本默认情况下,这是服务器端组件。 使用指令“使用客户端”在客户端环境中渲染此组件。 使用useref react with nextjs应用程序对我来说很好。
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">
...