簡體   English   中英

根據父尺寸渲染React子組件

[英]Render React child component based on parent dimensions

我需要從UV坐標渲染React子組件(標准化坐標/ U&V通常在[0; 1]范圍內)

但是我不知道在兒童渲染期間如何獲得父尺寸。

我想執行類似(使用tsx)的操作:

const Child = (props: {u:Number, v:Number}) => 
      <circle cx={parentClientWidth*props.u} cy={parentClientHeight*props.v} r="5" fill="black"></circle>;

const Parent = () => 
      <svg>
         <Child u={0.3} v={0.5} />
      </svg>;

我是否願意使用上下文對象?


const Child = (props: {u:Number, v:Number}) => {
      const workspace= useContext(WorkspaceContext);

      return <circle cx={workspace.width*u} cy={workspace.height*v} r="5"></circle>;
}

注意:在這種簡單情況下,我可以將百分數用於cx和cy坐標,但實際情況要復雜得多...

經過大量的反應文檔后,我終於找到了一種對我來說似乎不太hacky的方法...但是我仍在學習,因此可能還有另一種更好的方法(關於性能?可讀性?...)。我當前解決方案的想法:

// Shares the dimensions of the workspace through children
const WorkspaceContext = createContext();

/** A child component.
 * It should be placed at specified (u,v) within the parent component. 
 */
const Child = (props: {u:Number, v:Number}) => {
     const workspaceContext = useContext(WorkspaceContext);
     return <circle cx={workspaceContext.width*props.u} cy={workspaceContext.height*props.v} r="5" fill="black"></circle>;
};

/** The parent SVG component */
const Parent = () => {
      const [dimensions, setDimensions] = useState({
            width: undefined, 
            height:undefined, 
            outdated: true // Triggers a re render when changed
       });

      // I'm using the ref callback to get the svg dimensions
      const parentRefCallback = (element: SVGSVGElement) => {
        if(element) {
            const width = element.clientWidth;
            const height = element.clientHeight;
            if(dimensions.width !== width || dimensions.height !== height) {
                setDimensions({width, height, outdated: false});
            }
        }
    };

    useEffect(() => {
        const handler = () => setDimensions({...dimensions, outdated: true}); // re renders!
        window.addEventListener('resize', handler);
        return () => window.removeEventListener('resize', handler);
    }, [])

      return <svg ref={parentRefCallback}>
         <WorkspaceContext.Provider value={dimensions}>
             <Child u={0.3} v={0.5} />
         </WorkspaceContext.Provider>
      </svg>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM