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>
  )
}
相关推荐
测试界柠檬1 分钟前
面试真题 | web自动化关闭浏览器,quit()和close()的区别
前端·自动化测试·软件测试·功能测试·程序人生·面试·自动化
多多*2 分钟前
OJ在线评测系统 登录页面开发 前端后端联调实现全栈开发
linux·服务器·前端·ubuntu·docker·前端框架
2301_801074152 分钟前
TypeScript异常处理
前端·javascript·typescript
ᅠᅠᅠ@3 分钟前
异常枚举;
开发语言·javascript·ecmascript
小阿飞_4 分钟前
报错合计-1
前端
caperxi5 分钟前
前端开发中的防抖与节流
前端·javascript·html
霸气小男5 分钟前
react + antDesign封装图片预览组件(支持多张图片)
前端·react.js
susu10830189116 分钟前
前端css样式覆盖
前端·css
学习路上的小刘8 分钟前
vue h5 蓝牙连接 webBluetooth API
前端·javascript·vue.js
&白帝&8 分钟前
vue3常用的组件间通信
前端·javascript·vue.js