Javascript 如何从导入SVG组件获取维度-nextJS
我将SVG文件作为组件导入,并尝试获取其维度,但它返回null。谁能给我一些建议来实现这一点 PS.getBBox()不起作用,请给我一个错误 代码示例:Javascript 如何从导入SVG组件获取维度-nextJS,javascript,reactjs,svg,next.js,Javascript,Reactjs,Svg,Next.js,我将SVG文件作为组件导入,并尝试获取其维度,但它返回null。谁能给我一些建议来实现这一点 PS.getBBox()不起作用,请给我一个错误 代码示例: import IconSVG from 'public/images/my-svg.svg'; const MyComponent = () => { const myRef = React.useRef(null); React.useEffect(() => { console.log(myRef.cu
import IconSVG from 'public/images/my-svg.svg';
const MyComponent = () => {
const myRef = React.useRef(null);
React.useEffect(() => {
console.log(myRef.current);
}, []);
return (
<div>
<IconSVG ref={myRef} />
</div>
);
};
从“public/images/my svg.svg”导入IconSVG;
常量MyComponent=()=>{
const myRef=React.useRef(null);
React.useffect(()=>{
console.log(myRef.current);
}, []);
返回(
);
};
相反,您必须使用:
constmycomponent=()=>{
const myRef=React.useCallback(节点=>{
如果(节点!==null){
console.log(node.current.getBoundingClientRect());//获取维度
}
}, []);
返回(
);
};
根据svg的格式,您可以获得viewBox
属性,有时svg还具有width
和height
属性。谢谢!直到现在我才知道ref的回调,很高兴这有帮助。
const MyComponent = () => {
const myRef = React.useCallback(node => {
if (node !== null) {
console.log(node.current.getBoundingClientRect()); // get dimensions
}
}, []);
return (
<div>
<IconSVG ref={myRef} />
</div>
);
};