接上一篇内容继续实现功能:含有子元素则移除,不含有则添加一个类名为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>
)
}