[英]How to remove the child element of a div in react using useRef hook?
我想刪除舊的 SVG 並在 chart_data 值更改時創建一個新的 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 = "";
我使用了上面的答案,即您應該在removeChild()方法中指示子元素。 但它會拋出一個錯誤,我是這樣處理的:
if (chart.current.children[0]) { chart.current.removeChild(chart.current.children[0]); }
所以它會檢查孩子是否存在,然后將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.