onClick

时间:2017-07-08 17:34:44

标签: javascript reactjs ecmascript-6

我正在尝试在按下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>
    );
  }

它将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>

(我剪掉了剩下的代码,因为它很长,在这里没用)

将数组(单独的文件)导入Parent组件,其内容如下所示

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

export default players;

所以我想要做的就是在主要父母上写一个函数,当它在孩子里面被点击时,div被移除,删除,消失(无论最好的术语是什么)有点像&# 34;删除玩家,添加玩家&#34;

在我的父组件上,我编写了一个函数,当console.log在子项中被单击时,其工作正常,但是我在函数中写的任何东西似乎都不想工作。

我正在建设的功能(正在进行中,我仍然有点迷失):

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

在这里被映射为道具

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

在这里传给孩子:

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>

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

3 个答案:

答案 0 :(得分:5)

我们在聊天中对它进行了整理。像预期的那样,这是国家的问题。

我制作了一个小的半伪片段,其中包含注释:

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

....

答案 1 :(得分:1)

很少混淆整个应用程序的工作原理,但我会尽力帮助你。

要使反应更改为dom,您必须将players放入state。所以,在removePlayer中你在局部变量中复制了this.state.players(只是为了不直接在state中更改数组,这是一个很好的实践),然后你进行拆分这个局部变量,最后是你setState({ players: localPlayers})

这样就可以删除“div”。

答案 2 :(得分:0)

这是我解决此问题的方式

我已经为元素添加了一个ID 然后使用功能删除我毁了它

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

NB:元素在当前文档中被破坏 所以在当前渲染中

在Next JS上,它运行完美

如果您正在使用带有React的实时渲染,则可能无法正常工作

在这种情况下,我建议您与各州合作