按下按钮时删除选中的项目

时间:2016-05-15 13:24:47

标签: reactjs

实现这个目标的反应方式是什么?

我应该将复选框设置为子组件吗? - > 如何将删除事件传递给子组件?

如果我没有设置复选框作为子组件,我需要一个for循环来遍历每个项目并检查它是否被选中,如果为true则删除

我确信这是一个优雅的解决方案,但我是React的新手,我还没有理解这些概念 - 所以,如果有任何额外的阅读可以帮助提高我的理解,请告诉我! / p>

2 个答案:

答案 0 :(得分:0)

我现在能想到的最简单的方法是拥有一个包含复选框数组的组件(或至少是复选框状态)。该组件将显示复选框以及一个按钮,单击该按钮将迭代阵列并删除所有选中的框。

如果您不想将所有内容保存在一个组件中,有多种方法可以实现此目的。例如,您可以轻松地将按钮和复选框数组保存在父组件中,并将该数组作为prop传递给子组件。

您可能需要查看flux,这是一种处理应用程序状态(复选框数组)的方法。通量的流行实现是redux

您也可以使用React without flux(如上所示),这里有一篇关于8 no-flux stragergies for react component communication的文章。

答案 1 :(得分:0)

基本上,父组件会跟踪子项列表以及要删除的子项列表。每次选中一个复选框时,它都会被添加到删除列表中,如果未选中则会从删除列表中删除。当按下删除按钮时,删除列表中的每个项目都从子列表中删除,清除删除列表,并调用setState重新呈现组件。

import React from 'react';
import ReactDOM from 'react-dom';

class Form extends React.Component {
  constructor(props) {
    super(props)
  }
  // A delete-list and a list of children.
  state = {
    toDel: [],
    checks: []
  }
  // Method called when checkbox is clicked.
  recId = (idToDel) => {
    // Grab the checkbox that was clicked.
    let checker = document.getElementById(idToDel);
    if (checker.checked) {
      // Add the id to delete-list.
      this.state.toDel.push(idToDel);
    }
    else {
      // Remove the id from delete-list.
      let index = this.state.toDel.indexOf(idToDel);
      this.state.toDel.splice(index, 1);
    }
  }
  // Method called when delete button is clicked.
  del = () => {
    // Loop through items to delete.
    for (var i = 0; i < this.state.toDel.length; i++) {
      // Convert id from string back to integer.
      let index = parseInt(this.state.toDel[i])
      // Replace the item to delete with empty string, so that every
      // other element remains in place.
      this.state.checks[index] = '';
    }
    // Re-render the component by calling setState.
    this.setState({
      toDel: [],
      checks: this.state.checks
    });
  }
  // Loading the component with child checkboxes. Children are handed
  // parent methods as event handlers.
  componentWillMount = () => {
    for (var i = 0; i < 5; i++) {
      this.state.checks.push(
        <p key={i}>
          <Check id={i.toString()} record={this.recId} />{i.toString()}
        </p>
      )
    }
  }
  render () {
    return (
      <div>
        {this.state.checks}
        <button onClick={this.del}>Delete</button>
      </div>
    );
  }
}

class Check extends React.Component {
  constructor(props) {
    super(props)
  }
  state = {}
  render = () => {
    // Call the parent method on click with proper context and pass
    // id of this specific child back up to parent.
    return (
      <input type='checkbox' onClick={this.props.record.bind(null, this.props.id)} id={this.props.id} />
    );
  }
}

// Render component.
ReactDOM.render(
  <Form />,
  document.getElementById('test-container')
);
相关问题