Estoy tratando de calcular el ancho del componente secundario. ¿Es posible calcular el ancho de los componentes secundarios? aquí está mi código aquí está mi código https://codesandbox.io/s/reverent-hermann-yt7es?file=/src/App.js
<Tabs> {data.map((i) => ( <li>{i}</li> ))} </Tabs>TABLAS.js
import React, { useEffect, useRef } from "react"; const Tabs = ({ children }) => { const tabsRef = useRef(null); const setTabsDimensions = () => { if (!tabsRef.current) { return; } // initial wrapper width calculation const blockWidth = tabsRef.current.offsetWidth; // const showMoreWidth = moreItemRef.current.offsetWidth; // calculate width and offset for each tab let tabsTotalWidth = 0; const tabDimensions = {}; children.forEach((tab, index) => { if (tab) { console.log(tab); // const width = !isMobile ? 200 : 110; // tabDimensions[index] = { // width, // offset: tabsTotalWidth // }; // tabsTotalWidth += width; } }); }; useEffect(() => { setTabsDimensions(); }); return ( <ul ref={tabsRef} className="rc64nav"> {children} </ul> ); }; export default Tabs;Sé que al usar ref podemos acceder a la propiedad dom, pero cómo aplicar ref en el elemento de elementos secundarios. aquí estoy tratando de calcular el ancho de todos los artículos
children.forEach((tab, index) => { if (tab) { console.log(tab);Simplemente responda a su pregunta sobre cómo obtener la referencia del niño.
const Parent = () => { const childRef = useRef() // An example of use the childRef const onClick = () => { if (!childRef.current) return console.log(childRef.current.offsetWidth) } return <Child childRef={childRef} /> } const Child = ({ childRef }) => { return <div ref={childRef}>Hello Child</div> } NOTA: la forma en que paso ref aquí es exactamente la misma forma en que pasa el método principal al secundario. Y también ref admite dos formatos, estoy usando el simple, pero también puede usar el formato () => {} . https://reactjs.org/docs/refs-and-the-dom.html