Javascript 如何在React中获取子元素的样式(offsetTop)?
我需要得到h1的子组件的样式(在这个例子中是偏移),有什么想法吗Javascript 如何在React中获取子元素的样式(offsetTop)?,javascript,reactjs,Javascript,Reactjs,我需要得到h1的子组件的样式(在这个例子中是偏移),有什么想法吗 const App = () => { return ( <Comp> <h1>Title</h1> <p> ... </p> </Comp> ); } const-App=()=>{ 返回( 标
const App = () => {
return (
<Comp>
<h1>Title</h1>
<p> ... </p>
</Comp>
);
}
const-App=()=>{
返回(
标题
);
}
在这里,我递归地遍历“Comp”组件的所有子级,以获得每个h1的偏移量
const Comp = ({children}) => {
React.useEffect(() => {
const traverse = (paramChildren) => {
React.Children.forEach(paramChildren, (child) => {
if(child.type === "h1")
// Here i need to get the offsetTop of child
if(Array.isArray(child?.props?.children))
traverse(child.props.children);
});
}
traverse(children);
},[])
return <>...</>;
}
const Comp=({children})=>{
React.useffect(()=>{
常量遍历=(参数子项)=>{
React.Children.forEach(paramChildren,(child)=>{
如果(child.type==“h1”)
//在这里,我需要得到孩子的补偿
if(Array.isArray(child?props?children))
遍历(child.props.children);
});
}
(儿童);
},[])
返回。。。;
}
是,它工作正常,但我无法获得子组件样式