我有一個父組件,它在螢屏上重復一個通用的子 SVG 組件。
為此,父組件需要知道子組件的尺寸。
我曾經像這樣將它們存盤在子組件中(我知道這很不尋常,但它有效)
function Child() {
return <path id="child" />
}
Child.width = 100
Child.height = 80
然后我曾經像這樣在我的父組件上閱讀它們
function Parent(props) {
let width = props.children.type.width
let height = props.children.type.height
return Array.from(Array(props.times), (e, i) => {
return <Transform key={i} x={width*i} y={height*i}>
{props.children}
</Transform>
})
}
我想要的是父容器自己計算孩子的尺寸,所以它們不是靜態的。
我知道我需要使用這樣的 ref 訪問孩子的 dom
function Parent(props) {
const test = React.useCallback(node => {
if (node !== null) {
const box = node.getBBox()
console.log(box) //this works
var width = box.width //this works too late
var height = box.height
}
}, []);
return Array.from(Array(props.times), (e, i) => {
return <Transform key={i} x={width*i} y={height*i}>
<g ref={test}> {props.children}</g>
</Transform>
})
}
但正如我想象的那樣,React 不會等待我的回呼來執行其余的代碼,所以它說寬度和高度是未定義的。
我怎樣才能獲得第一個元素的寬度和高度,然后讓 Parent 組件完成他的作業?也許有懸念?非常感謝任何幫助,謝謝!
uj5u.com熱心網友回復:
首先,您可以通過 url 使用 svg 作為背景影像并放置背景重復和調整大小。但是,如果您想要這種方法,我們就去吧。使用 forwardRef/refs 有很多方法可以實作這種效果。下面的代碼是我首先想到的我建議讓你 svg 作為 jsx/tsx 檔案/反應組件 - 這樣,否則你需要將 parentRef 提供到 layoutEffect 依賴項中
import React, { useLayoutEffect, useRef } from 'react';
import logo from './logo.svg';
import './App.css';
import Logo from './Logo';
const Parent1: React.FC = ({ children }) => {
const parentRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
parentRef.current?.childNodes.forEach((node: any) =>
console.log({ height: node?.clientHeight, width: node?.clientWidth }),
);
}, []);
return (
<div className='parent1' ref={parentRef}>
{children}
</div>
);
};
function App() {
return (
<div className='App'>
<Parent1>
{Array(Math.ceil(Math.random() * 25 10))
/**
If you will decide to go img way - you need to place
parentRef as a dependancy for the layoutEffect
.fill(() => <img src={logo} alt='' />)
*/
.fill(Logo)
.map((E, i) => {
return <E key={i} />;
})}
</Parent1>
</div>
);
}
uj5u.com熱心網友回復:
因此解決方案是在 useEffect 中更新組件的狀態,以便在資料可用時更新我們的視圖:
function Parent(props) {
const [height, setHeight] = React.useState()
const [width, setWidth] = React.useState()
const test = React.useCallback(node => {
if (node !== null) {
const box = node.getBBox()
setWidth(box.width)
setHeight(box.height)
}
}, []);
return Array.from(Array(props.times), (e, i) => {
return <Transform key={i} x={width*i} y={height*i}>
<g ref={test}> {props.children}</g>
</Transform>
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459437.html
標籤:javascript 反应 svg 同步 参考
上一篇:通過單擊鏈接下載svg檔案
