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>
  )
}
相关推荐
沙蒿同学2 小时前
不引 Ghostscript:我用纯 Go 给 PDF 做了一场「压缩手术」
前端·后端·github
Linux_cy2 小时前
服务器管理工具哪个好用?我用了七八个
运维·服务器·javascript·python·ssh·面板·gmssh
变与不变8062 小时前
jQuery细节以及使用应用场景
前端·javascript·jquery
SailingCoder4 小时前
【封闭结束1】端到端交付:Agent 一次请求如何走完全链路
前端·安全·ai·面试·agent·harness
风骏时光牛马6 小时前
AI多模块协同自动化工作流
前端
zhangminghuan6 小时前
前端面试应对技巧
前端·面试·职场和发展
计算机魔术师6 小时前
潜伏14年的PHP致命洞,AI跑两天就交卷了
前端
IT_陈寒7 小时前
Vue的这个响应式陷阱我居然现在才发现
前端·人工智能·后端
Python自动化直播8 小时前
智能脚本批量管理拆开看:导入、导出、重写、试听
前端·python·ai·秒播