Home >Web Front-end >Front-end Q&A >How to delete dom elements in react
React method to delete dom elements: 1. Use the render life cycle to define a DOM node variable; 2. Delete dom elements through "onClickS(){this.setState({deled:false})}" That’s it.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to delete dom elements in react?
react Delete (hide) and add (display) element DOM nodes
Usually delete (hide) and add (display) Many people use the none style of css display to achieve this There is a disadvantage. F12 can just change the style directly. It is very unsafe. We should implement real deletion and addition, but in react's view, it can also be called rendering or not rendering this component. This dom
react has the removeChild method but does not have appendChild. Method so we can only update the page through render combined with the state method
That is, using the render life cycle to define a variable DOM node variable
Then use state to update the value of whether to display
import React from 'react'; class Page2 extends React.Component { constructor(props) { super(props); this.state={ deled:true } this.onClick=this.onClick.bind(this) this.onClickS=this.onClickS.bind(this) } //恢复 onClick(){ this.setState({ deled:true }) } //删除 onClickS(){ this.setState({ deled:false }) } render() { const { deled} = this.state; var showMap=''; //三元表达式判断deled的值来更新showMap deled==true?showMap=<img src={require('../image/joinwechat/s.png')}></img>:showMap=''//这是一张二维码图 return ( < > <button onClick={this.onClickS}>点我删除二维码</button> <button onClick={this.onClick}>点我恢复二维码</button> {showMap} </> ) } } export default Page2;
Recommended learning: "react video tutorial"
The above is the detailed content of How to delete dom elements in react. For more information, please follow other related articles on the PHP Chinese website!