admin管理员组

文章数量:1193971

I am trying to remove a div when onClick is pressed. The div exists on my parent component where I have

 render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
        removePlayer={this.removePlayer}
        handleClick={player}
      />
    ));

    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>
        <div>
          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}
        </div>
      </ContainLeft>
    );
  }

It passes props to the child component where the button to delete the div, here

    return (
      <div
        style={{ display: this.state.displayInfo }}
        className="group-list"
        ref={sortableGroupDecorator}
        id="cell"
      >
        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
            <Col>
              <DeleteButton onClick={removePlayer}>
                <Icon name="delete" className="delete-adjust fa-minus-circle" />
              </DeleteButton>
            </Col>

(I snipped the rest of the code because it was long and not useful here)

The array (a separate file) is imported into the Parent component and it reads like this

const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

export default players;

So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"

On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.

The function I'm building (in progress, I'm still a little lost here) is:

  removePlayer() {
    console.log('this was removed');
    players.splice(2, 0, 'Luke', 'Vader');
  }

which is mapped over here as a prop

const listPlayers = players.map(player => (
  <Counter
    key={player.id}
    player={player}
    name={player.name}
    sortableGroupDecorator={this.sortableGroupDecorator}
    decrementCountTotal={this.decrementCountTotal}
    incrementCountTotal={this.incrementCountTotal}
    removePlayer={this.removePlayer}
    handleClick={player}
  />
));

And passed into the child here:

render() {
const {
  name,
  sortableGroupDecorator,
  decrementCountTotal,
  incrementCountTotal,
  removePlayer
} = this.props;

return (
  <div
    style={{ display: this.state.displayInfo }}
    className="group-list"
    ref={sortableGroupDecorator}
    id="cell"
  >
    <CountCell style={{ background: this.state.color }}>
      <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
        <Col>
          <DeleteButton onClick={removePlayer}>
            <Icon name="delete" className="delete-adjust fa-minus-circle" />
          </DeleteButton>

I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages. Thanks for helping out in advance

I am trying to remove a div when onClick is pressed. The div exists on my parent component where I have

 render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
        removePlayer={this.removePlayer}
        handleClick={player}
      />
    ));

    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>
        <div>
          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}
        </div>
      </ContainLeft>
    );
  }

It passes props to the child component where the button to delete the div, here

    return (
      <div
        style={{ display: this.state.displayInfo }}
        className="group-list"
        ref={sortableGroupDecorator}
        id="cell"
      >
        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
            <Col>
              <DeleteButton onClick={removePlayer}>
                <Icon name="delete" className="delete-adjust fa-minus-circle" />
              </DeleteButton>
            </Col>

(I snipped the rest of the code because it was long and not useful here)

The array (a separate file) is imported into the Parent component and it reads like this

const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

export default players;

So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"

On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.

The function I'm building (in progress, I'm still a little lost here) is:

  removePlayer() {
    console.log('this was removed');
    players.splice(2, 0, 'Luke', 'Vader');
  }

which is mapped over here as a prop

const listPlayers = players.map(player => (
  <Counter
    key={player.id}
    player={player}
    name={player.name}
    sortableGroupDecorator={this.sortableGroupDecorator}
    decrementCountTotal={this.decrementCountTotal}
    incrementCountTotal={this.incrementCountTotal}
    removePlayer={this.removePlayer}
    handleClick={player}
  />
));

And passed into the child here:

render() {
const {
  name,
  sortableGroupDecorator,
  decrementCountTotal,
  incrementCountTotal,
  removePlayer
} = this.props;

return (
  <div
    style={{ display: this.state.displayInfo }}
    className="group-list"
    ref={sortableGroupDecorator}
    id="cell"
  >
    <CountCell style={{ background: this.state.color }}>
      <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
        <Col>
          <DeleteButton onClick={removePlayer}>
            <Icon name="delete" className="delete-adjust fa-minus-circle" />
          </DeleteButton>

I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages. Thanks for helping out in advance

Share Improve this question edited Jul 9, 2017 at 3:29 OLIVER.KOO 5,9933 gold badges34 silver badges70 bronze badges asked Jul 8, 2017 at 17:34 sthigsthig 4693 gold badges13 silver badges36 bronze badges 7
  • 2 You might want to consider putting the players into the state, since the component won't rerender if you just change an out-of-scope variable. – Cynigo Commented Jul 8, 2017 at 17:40
  • so on the parent component I'd put this.state = {players: players};? – sthig Commented Jul 8, 2017 at 17:45
  • Pretty much, yes. Don't put it in the render function though! Use either a lifecycle function like componentWillMount or put it in the constructor. Then in your render function always refer to this.state.players. Then in your removePlayer() function, copy the array from the state, mutate it (splice your player or whatever) and then call this.setState() with the mutated copy. – Cynigo Commented Jul 8, 2017 at 17:49
  • ok I understand the broad gist of things here, some things I'm not completely well versed on, but this is the first time I've understood how to do this (I've been plugging away for weeks at this). – sthig Commented Jul 8, 2017 at 17:51
  • Great. Good luck. hmu if you need some help. – Cynigo Commented Jul 8, 2017 at 17:52
 |  Show 2 more comments

3 Answers 3

Reset to default 10

We sorted it out in chat. Like expected, it was a problem with the state.

I made a small semi-pseudo snippet with comments as explanation:

import React, { Component } from 'react';

// Your player constant, outside the scope of any React component
// This pretty much just lives in your browser as a plain object.
const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

class App extends Component {

  constructor() {
    super();

    this.state = {
      players, // ES6 Syntax, same as players: players
      // Add all your other stuff here
    };
  }

  removePlayer(id) {
    const newState = this.state;
    const index = newState.players.findIndex(a => a.id === id);

    if (index === -1) return;
    newState.players.splice(index, 1);

    this.setState(newState); // This will update the state and trigger a rerender of the components
  }

  render() {

   const listPlayers = this.state.players.map(player => { // Note the this.state, this is important for React to see changes in the data and thus rerender the Component
      <Counter
        ..

        removePlayer={this.removePlayer.bind(this)} //bind this to stay in the context of the parent component
      />
    });

    return (
      <div>
        {listPlayers}
      </div>
    );
  }
}





//////////////////////////////////////// Child component

....

<DeleteButton onClick={() => this.props.removePlayer(this.props.player.id)}>

....

Here is how i solved this

i've added an id to the element and then with function remove i detroyed it

const closenotif = () => document.getElementById("notif").remove()
 
<div id="notif">
       <button onClick={destroy}> close </button>
</div> 

NB : the element is destroyed in the current document so in the current render

on Next JS this works perfectly

if you are using a live rendering with react this probably won't work

i'll suggest you to work with states in that case

Little confused about how the whole app works, but I will try to help you.

To make react changes to the dom, you have to put players in the state. So, in the removePlayer you make a copy of this.state.players in a local variable (just to not change the array directly in state, it's a good practice), then you make the split in this local variable and finally you setState({ players: localPlayers}).

This way the "div" will be removed.

本文标签: javascriptReact removing an element when onClickStack Overflow