如何使用useRef钩子删除react中div的子元素



每当chart_data值发生变化时,我想删除旧的SVG并创建一个新的SVG。

import React, {useRef, useEffect, useState} from 'react'
import * as d3 from 'd3'
import { useSelector} from "react-redux";
const Barchart = () =>{
const chart = useRef(null);
const chart_data= useSelector(state => state.ChartReducer);
useEffect(() => {
let svg = d3.select(chart.current)
//code to create the chart
//
return () => {
//How to remove the old svg element from the ref chart.current?
//I tried
chart.current.removeChild() // This throws an error saying expects 1 argument got 0
}
},[chart_data])
return(
<div className="bar-chart" ref={chart}></div>
)
}
export default Barchart

chart.current.removeChild()未删除<div className="bar-chart" ref={chart}></div>的子级

如何删除具有useRef引用的div的所有子元素?

您应该在removeChild()方法中指示子元素。

chart.current.removeChild(chart.current.children[0])

Node.removeChild((要求移除子节点作为参数。如果你想删除所有的子元素,你可以使用element.innerHTML:

chart.current.innerHTML = "";

Node.removeChild()需要一个丢失的节点参数(要删除的子节点(。

这个问题没有React的具体内容。

你是说吗

chart.current.removeChild(svg)

我使用了上面的答案,即您应该在removeChild((方法中指示子元素。但它抛出了一个错误,我是这样处理的:

if (chart.current.children[0]) {
chart.current.removeChild(chart.current.children[0]);
}

因此,它会检查孩子是否存在,然后将其移除。

最新更新