javascript 如何使用 ReactJS 中的单击事件从列表中删除项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27817241/
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-10-28 08:02:16  来源:igfitidea点击:

how to remove an item from a list with a click event in ReactJS?

javascriptreactjs

提问by chovy

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

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.

我似乎无法理解如何从列表中删除项目。可能在这里也做出了很多其他糟糕的设计决定,新手。

回答by Ashley 'CptLemming' Wilson

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

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

A simplified example of this.

一个简化的例子

FilterApppasses a remove function to FilterListthat is called on the onClickevent. This will remove an item from the parent, update the state, then cause FilterListto re-render with the new content.

FilterApp将移除函数传递给FilterListonClick事件上调用的函数。这将从父项中删除一个项目,更新状态,然后FilterList使用新内容重新渲染。

Hope this helps.

希望这可以帮助。

回答by TYRONEMICHAEL

Something like the below should work. Let your root component manage state.

像下面这样的东西应该可以工作。让您的根组件管理状态。

var FilterList = React.createClass({
  render: function() {
    var createItem = function(item) {
      return (
        <li>
          <span>{item}</span>
          <a href data-id="{item.id}" class="remove-filter" onClick={this.props.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
      }
    });
  },
  remove: function(item, ev){
    ev.preventDefault();

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

    this.setState({ items: items });
  },
  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 remove={this.remove} 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);