每当 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 的所有子元素?
答案 0 :(得分:1)
您应该在 removeChild()
方法中指明子元素。
chart.current.removeChild(chart.current.children[0])
答案 1 :(得分:1)
Node.removeChild() 要求将子节点作为参数删除。如果要删除所有子元素,可以使用 Element.innerHTML:
chart.current.innerHTML = "";
答案 2 :(得分:0)
Node.removeChild()
需要一个您缺少的节点参数(要删除的子节点)。
React 中没有针对此问题的任何内容。
你可能是说
chart.current.removeChild(svg)
?