如何使用ref访问map函数的子函数并更改其样式?
这是我的联署材料:
<NodeStyles.Container >
<div className="circle" id="container" ref={ref}>
{items?.map((el, index) => (
<Nodes
changeCenterNode={changeCenterNode}
setCenterNode={setCenterNode}
setfadeIn={setfadeIn}
key={index}
relations={el.Relations}
index={index}
el={el}
ParentUnique={el.ParentUnique}
/>
))}
</div>
</NodeStyles.Container>
这是我的useEffect:
useEffect(() => {
// ️ use a ref (best)
const items = ref.current.children;
for (var i = 0, l = items.length; i < l; i++) {
items[i].style.left =
(
54 -
140 * Math.cos(-0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)
).toFixed(4) + "%";
items[i].style.top =
(
20 +
140 * Math.sin(-0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)
).toFixed(4) + "%";
}
}, [items, ref]);
当我使用map函数时,我不能用ref来改变孩子的风格。如何更改节点组件的样式?
在我的节点组件中,我有三个div标记
//Nodes Component
...
return (
<div>
<div>1</div>
<div>2</div>
<div>3</div>
</div>
) ;
发布于 2022-10-30 22:55:21
你的裁判指的是什么?据我所知,您可能只对类组件和html元素使用ref属性,因为根据文档说明。
--您可能不会对函数组件使用ref属性,因为它们没有实例。https://reactjs.org/docs/refs-and-the-dom.html
如果情况恰好是这样,为什么不直接将样式传递给孩子,如果你想把它应用到所有的孩子身上,你可以通过使用React.Children.toArray
来使孩子变平,然后映射和应用你的样式,否则你必须检查它是什么类型的。
另一个选项是创建包装器组件,使用更好的克隆元素,您可以在不干扰其他道具等的情况下应用任何样式,它可以如下所示
const Wrapper= ({ children }) => {
return React.cloneElement(children, {
style: {
'left':
(
54 -
140 * Math.cos(-0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)
).toFixed(4) + "%",
'top':
(
20 +
140 * Math.sin(-0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)
).toFixed(4) + "%"
},
})
};
希望这能有所帮助
https://stackoverflow.com/questions/74259322
复制相似问题