繁体   English   中英

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

[英]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 = "";

Node.removeChild()需要您缺少的节点参数(要删除的子节点)。

这个问题没有什么 React 特有的。

你是不是想说

chart.current.removeChild(svg)

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

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

所以它会检查孩子是否存在,然后将其删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM