Home  >  Article  >  Web Front-end  >  How to delete dom elements in react

How to delete dom elements in react

藏色散人
藏色散人Original
2022-12-27 09:39:312786browse

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.

How to delete dom elements in react

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(&#39;../image/joinwechat/s.png&#39;)}></img>:showMap=&#39;&#39;//这是一张二维码图
        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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn