如何在ReactJS中使用单击事件从列表中删除项目? [英] how to remove an item from a list with a click event in ReactJS?

查看:66
本文介绍了如何在ReactJS中使用单击事件从列表中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var FilterList = React.createClass({
  remove: function(item){

    this.props.items = this.props.items.filter(function(itm){
      return item.id !== itm.id;
    });

    return false;
  },
  render: function() {
    var createItem = function(item) {
      return (
        <li>
          <span>{item}</span>
          <a href data-id="{item.id}" class="remove-filter" onClick={this.remove.bind(item)}>remove</a>
        </li>

      );
    };
    return <ul>{this.props.items.map(createItem.bind(this))}</ul>;
  }
});
var FilterApp = React.createClass({
  getInitialState: function() {
    return {items: [], item: {
      id: 0,
      type: null
    }};
  },
  onChangeType: function(e){
    this.setState({
      item: {
        id: this.state.items[this.state.items.length],
        type: e.target.value
      }
    });
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextItems = this.state.items.concat([this.state.item]);
    var item = {};
    this.setState({items: nextItems, item: {}});
  },
  render: function() {
    return (
      <div>
        <h3>Filters</h3>
        <FilterList items={this.state.items} />

        <form className="filter" onSubmit={this.handleSubmit}>
          <fieldset>
            <legend>Filter</legend>
            <div className="form-grp">
              <select name="type" onChange={this.onChangeType}>
                <option>foo</option>
                <option>bar</option>
                <option>baz</option>
              </select>
            </div>
          </fieldset>
          <div className="actions">
            <button>{'Add #' + (this.state.items.length + 1)}</button>
          </div>
        </form>
      </div>
    );
  }
});

React.render(<FilterApp />, document.body);

我似乎无法理解如何从列表中删除项目。可能在这里做出大量其他糟糕的设计决定,newbs。

I cannot seem to wrap my head around how to remove an item from the list. Probably making a ton of other bad design decisions here too, newbs.

推荐答案

组件上的道具是不可变的,这意味着你无法修改它们直。在上面的示例中,如果 FilterList 组件想要删除项目,则需要从父组件调用回调。

Props on components are immutable, meaning you cannot modify them directly. In your above example if the FilterList component wants to remove an item, it would need to call a callback from the parent component.

简化的此示例

FilterApp 将删除函数传递给 onClick上调用的 FilterList 事件。这将从父项中删除项目,更新状态,然后使 FilterList 重新呈现新内容。

FilterApp passes a remove function to FilterList that is called on the onClick event. This will remove an item from the parent, update the state, then cause FilterList to re-render with the new content.

希望这会有所帮助。

这篇关于如何在ReactJS中使用单击事件从列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆