最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove DOM in react.js, - Stack Overflow

programmeradmin0浏览0评论

How do I remove the item when user clicked x? pass the id to parent and use filter()? In jquery I can just use remove() and that's about it. Very new to react, need guidance.

import React from 'react';

const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => 
        <li className='list-group-item' data-id={item.id} key={i}>{item.name}
        <button className="btn btn-sm btn-primary onClick={}">X</button>
        </li>
      )}
      </ul>
    ) 
};

const TodoItems = React.createClass({
  getInitialState() {
    return {
      items: [
        {id:1,name:"Gym"},
        {id:2,name:"Jump"},
        {id:3,name:"Racing"}
      ],
      editing: false
    }
  },
  edit(){
    this.setState({editing: true})
  },
  save(){
    this.setState({editing: false})
  },
  remove(id){
    //return this.items.filter((item,i) => item.id !== id)
  }
  render(){
    return(
      <RenderItem items={this.state.items} />
    ) 
  }
})


ReactDOM.render(
  <TodoItems />,
  document.getElementById('container')
);
<div id="container">
</div>


<script src=".1.0/react.min.js"></script>
<script src=".1.0/react-dom.min.js"></script>

How do I remove the item when user clicked x? pass the id to parent and use filter()? In jquery I can just use remove() and that's about it. Very new to react, need guidance.

import React from 'react';

const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => 
        <li className='list-group-item' data-id={item.id} key={i}>{item.name}
        <button className="btn btn-sm btn-primary onClick={}">X</button>
        </li>
      )}
      </ul>
    ) 
};

const TodoItems = React.createClass({
  getInitialState() {
    return {
      items: [
        {id:1,name:"Gym"},
        {id:2,name:"Jump"},
        {id:3,name:"Racing"}
      ],
      editing: false
    }
  },
  edit(){
    this.setState({editing: true})
  },
  save(){
    this.setState({editing: false})
  },
  remove(id){
    //return this.items.filter((item,i) => item.id !== id)
  }
  render(){
    return(
      <RenderItem items={this.state.items} />
    ) 
  }
})


ReactDOM.render(
  <TodoItems />,
  document.getElementById('container')
);
<div id="container">
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

This is my code on fiddle https://jsfiddle.net/3mn105sj/, I don't know why I failed to use react here.

Share Improve this question edited Oct 2, 2016 at 17:02 Thian Kian Phin asked Oct 2, 2016 at 16:45 Thian Kian PhinThian Kian Phin 9313 gold badges13 silver badges27 bronze badges 1
  • Use a separate component and implement it there. – Gerard van Helden Commented Oct 2, 2016 at 16:47
Add a comment  | 

5 Answers 5

Reset to default 6

Check the fiddle:

https://jsfiddle.net/zp5oqnsh/1/

const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => 
        <li className='list-group-item' data-id={item.id} key={i}>{item.name}
        <button className="btn btn-sm btn-primary" onClick={() => props.remove(item.id)}>X</button>
        </li>
      )}
      </ul>
    ) 
};

const TodoItems = React.createClass({
  getInitialState() {
    return {
      items: [
        {id:1,name:"Gym"},
        {id:2,name:"Jump"},
        {id:3,name:"Racing"}
      ],
      editing: false
    }
  },
  edit(){
    this.setState({editing: true})
  },
  save(){
    this.setState({editing: false})
  },
  remove(id){
  this.setState({
    items: this.state.items.filter((el) => id !== el.id)
  })
    //return this.items.filter((item,i) => item.id !== id)
  },
  render(){
    return(
      <RenderItem items={this.state.items} remove={this.remove}/>
    ) 
  }
})


ReactDOM.render(
  <TodoItems />,
  document.getElementById('container')
);

Pass the remove() as a props and call the remove() onClick with the id and apply filter..

Hope it helps!

you need to use react-dom for example;

import { unmountComponentAtNode } from 'react-dom';

onDismiss(node) {
  unmountComponentAtNode(node);
  document.body.removeChild(node);
}

If you are creating a stateless component and passing props as argument, you can't use 'this.props'

const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => 
           <li className='list-group-item' data-id={item.id} key={i}>
               {item.name}
               <button 
                    className="btn btn-sm btn-primary" 
                    onClick={() => props.remove(item.id}>
                    X
               </button>
           </li>
      )}
      </ul>
)};

React is all about manipulating state to trigger rerenders of the DOM. Instead of arbitrarily removing the element from the DOM like you would in jQuery, you should update the state by filtering out the item from props.items which will trigger a rerender of the DOM with the item removed. This way, the item will still be removed from the DOM even after any subsequent rerenders - whereas with document.removeChild() or unmountComponentAtNode() the item will reappear after a subsequent rerender (in theory, I haven’t personally tested).

import React from 'react';
const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => 
        <li className='list-group-item' data-id={item.id} key={i}>{item.name}
        <button className="btn btn-sm btn-primary" onClick={() => props.remove(item.id)}>X</button>
        </li>
      )}
      </ul>
    ) 
};

const TodoItems = React.createClass({
  getInitialState() {
    return {
      items: [
        {id:1, name:"Gym"},
        {id:2, name:"Jump"},
        {id:3, name:"Racing"}
      ],
      editing: false
    }
  },
  edit(){
    this.setState({editing: true})
  },
  save(){
    this.setState({editing: false})
  },
  remove(id){
    this.setState((prev) => {
       ...state,
       items: prev.items.filter((item) => item[id] !== id)
    })
  }
  render(){
    return(
      <RenderItem items={this.state.items} remove={this.remove} />
    ) 
  }
})


ReactDOM.render(
  <TodoItems />,
  document.getElementById('container')
);

If you don’t want the item to be removed from props.items, then add something like an isCompleted key for each item. Update the state by toggling the item’s isCompleted key to true and have the DOM only render the items that isCompleted === false.

import React from 'react';
const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => {
            item.isCompleted === false && (
                <li className='list-group-item' data-id={item.id} key={i}> 
                {item.name}
                <button className="btn btn-sm btn-primary" onClick={() => 
                props.remove(item.id)}>X</button>
                </li>
          )}}
      </ul>
    ) 
};

const TodoItems = React.createClass({
  getInitialState() {
    return {
      items: [
        {id:1, name:"Gym", isCompleted: false },
        {id:2, name:"Jump", isCompleted: false },
        {id:3, name:"Racing", isCompleted: false }
      ],
      editing: false
    }
  },
  edit(){
    this.setState({editing: true})
  },
  save(){
    this.setState({editing: false})
  },
  remove(id){
    this.setState((prev) => {
       ...state,
       items: prev.items.map(item => (item.id === id ? Object.assign({}, item, { isCompleted: true }) : item))
    })
  }
  render(){
    return(
      <RenderItem items={this.state.items} remove={this.remove} />
    ) 
  }
})


ReactDOM.render(
  <TodoItems />,
  document.getElementById('container')
);

Alternatively, you can store the removed items in a new array.

In MY case I used the useEffect and worked just fine.

Like this:

const [clients, setClient] = useState([]);

useEffect(() =>{getData();},[clients]);

I have a remove function that removes the element in the database, and when the clients array change, the getData is fired and automatically updates the DOM.

发布评论

评论列表(0)

  1. 暂无评论