Javascript 当 onClick 删除元素时反应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44988996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:50:40  来源:igfitidea点击:

React removing an element when onClick

javascriptreactjsecmascript-6

提问by sthig

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

我试图在按下 onClick 时删除一个 div。div 存在于我的父组件上

 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

它传递props给子组件所在的按钮删除div,这里

    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"

所以我想做的是在主要的父级上写一个函数,当它在子级中被点击时,div 被删除、删除、消失(无论最好的术语是什么)有点像“删除播放器,添加播放器”

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.

在我的父组件上,我编写了一个函数,当在子组件中单击它时,console.log 会起作用,但是我在函数中编写的任何内容似乎都不起作用。

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

我知道这一切都很冗长,我想提供尽可能多的细节,因为 React 对我来说仍然是新手,我对一些措辞感到困惑。感谢您提前提供帮助

采纳答案by Cynigo

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)}>

....

回答by Henrique Oecksler Bertoldi

Little confuse how the whole app works, but I will try help you.

几乎不会混淆整个应用程序的工作方式,但我会尽力帮助您。

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

做出反应的变化DOM,你必须把playersstate。所以,在removePlayer你复制this.state.players一个局部变量(只是不直接改变数组state,这是一个很好的实践),然后你在这个局部变量中进​​行拆分,最后你setState({ players: localPlayers})

This way the "div" will be removed.

这样“div”将被删除。