react中判断某元素内是否含有子元素,有则将所有子元素移除,无则添加一个类名为append_class的div元素

接上一篇内容继续实现功能:含有子元素则移除,不含有则添加一个类名为append_class的div元素。

类组件实现代码

javascript 复制代码
import React, { Component, createRef } from 'react'

export default class App extends Component {
  constructor(props){
    super(props)
    this.divRef = createRef()
  }

  componentDidMount(){
    const element = this.divRef.current
    if (element) {
      if (element.hasChildNodes()) {
        console.log('该元素含有子元素');
        const childNodes = element.childNodes
        for (let i = childNodes.length - 1; i >= 0; i--) {
          element.removeChild(childNodes[i])
        }
      }else{
        console.log('该元素不含子元素');
        const appendChildEl = document.createElement('div')
        appendChildEl.className = "append_class"
        appendChildEl.innerText = "类组件新加入的元素"
        element.appendChild(appendChildEl)
      }
    }
  }

  render() {
    return (
      <div>
        <div ref={this.divRef}>
          <button>子元素</button>
        </div>
      </div>
    )
  }
}

函数组件实现代码

javascript 复制代码
import React, {useRef, useEffect} from 'react'

export default function App() {
  
  const divRef = useRef(null)

  useEffect(() => {
    const element = divRef.current
    if (element) {
      if (element.hasChildNodes()) {
        console.log('该元素含有子元素')
        const childNodes = element.childNodes
        for (let i = childNodes.length - 1; i >= 0; i--) {
          element.removeChild(childNodes[i])
        }
      } else {
        console.log('该元素不含子元素')
        const appendChildEl = document.createElement('div')
        appendChildEl.className = "append_class"
        appendChildEl.innerText = "函数组件新加入的元素"
        element.appendChild(appendChildEl)
      }
    }
  })

  return (
    <div>
      <div ref={divRef}>
        <button>检查子元素</button>
      </div>
    </div>
  )
}
相关推荐
bin915314 分钟前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
晴空万里藏片云2 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一2 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球2 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7232 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
无责任此方_修行中3 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
Σίσυφος19004 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端4 小时前
0基础学前端-----CSS DAY13
前端·css
dorabighead5 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
css趣多多5 小时前
案例自定义tabBar
前端