react中使用ref属性获取元素,并判断该元素内是否含有子元素

在react中,可以使用ref属性来获取到一个元素的引用,然后再使用ref.current来访问该元素的DOM节点,使用DOM API来判断这个元素是否含有子元素,要判断一个元素是否含有子元素,可以使用hasChildNodes(),其返回值为Boolean,下面分别使用类组件与函数组件来实现。

类组件实现代码

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

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

  componentDidMount(){
    if (this.divRef.current) {
      if (this.divRef.current.hasChildNodes()) {
        console.log('该元素含有子元素');
      }else{
        console.log('该元素不含子元素');
      }
    }
  }

  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(() => {
    if (divRef.current) {
      if (divRef.current.hasChildNodes()) {
        console.log('该元素含有子元素')
      } else {
        console.log('该元素不含子元素')
      }
    }
  })

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

以上就是实现代码,下一篇将在此基础上实现移除子元素。

相关推荐
鱼干~几秒前
【全栈知识点】全栈开发知识点
前端·人工智能·c#
英俊潇洒美少年1 分钟前
迷你 React 调度器(带优先级+时间切片)手写实现
前端·javascript·react.js
chQHk57BN5 分钟前
PWA开发指南:构建可离线使用的渐进式Web应用
前端
weixin_4080996712 分钟前
【保姆级教程】按键精灵调用 OCR 文字识别 API(从0到1完整实战 + 可运行脚本)
java·前端·人工智能·后端·ocr·api·按键精灵
xdl259917 分钟前
CSS flex 布局中没有 justify-items
前端·css
百撕可乐17 分钟前
WenDoraAi官网NextJS实战04:HTTP 请求封装与SSR
前端·网络·网络协议·react.js·http
Sestid20 分钟前
前端AI编程使用技巧(后续会更新cursor和claude code for vscode)
前端·vscode·ai编程·claude·cursor
freeWayWalker23 分钟前
Vue通用缩放容器
前端·javascript·vue.js
Hello--_--World31 分钟前
VUE:逻辑复用
前端·javascript·vue.js