我开始在我的代码中引入了一些React hooks,特别是useEffect
,但我无法确定我做的是否安全。基本上,我在hook内部在DOM上运行动画,并且我想确保这不会破坏任何DOM快照,例如。
下面是一个例子,它是我从完整的示例中修改的,以便简明地说明发生了什么:
export function GrowingCircle(props) {
const root = useRef(null); // This is the root element we draw to
// The actual rendering is done whenever the data changes
useEffect(() => {
const radius = props.width / 2;
d3.select(root.current)
.transition()
.duration(1000)
.attr("r", radius);
}, [props.width]);
return (
<svg width={props.width} height="100%">
<circle ref={root} cx="0" cy="0" r="0" fill="red" />
</svg>
);
}
我关心的部分是.transition()
将在1秒内频繁更新DOM,我不确定这是否会影响react渲染?
作为后续问题(通常我们无法控制动画渲染,就像这个例子一样)。如果circle
不再位于JSX中,会改变什么吗?
export function GrowingCircle(props) {
const root = useRef(null); // This is the root element we draw to
// The actual rendering is done whenever the data changes
useEffect(() => {
const radius = props.width / 2;
d3.select(root.current)
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("fill", "red")
.transition()
.duration(1000)
.attr("r", radius);
}, [props.width]);
return (
<svg ref={root} width={props.width} height="100%">
</svg>
);
}