React 工具箱可删除芯片

React toolbox deletable chips

我尝试添加很多筹码 (http://react-toolbox.com/#/components/chip) 但我真的无法使用 React...

link中的示例仅显示单个可删除芯片。只要有一个 Deletable Chip 就可以,但我无法让它与更多芯片一起使用。

这是我的代码:

import React, { PropTypes } from 'react';
import Chip from 'react-toolbox/lib/chip';

var Chiplist = [
    {'id': 1, 'title': 'Keyword 1'},
    {'id': 2, 'title': 'Keyword 2'},
    {'id': 3, 'title': 'Keyword 3'},
    {'id': 4, 'title': 'Keyword 4'}
 ];

class ChipsList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {deleted : {1: false, 2: false, 3: false, 4: false}};
    /*for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
    }*/
  }


 /* for(i = 0; i < Chiplist.length; $i++){
    state.deleted.i = false;
  }*/

  handleDeleteClick(index) {
    /*this.setState({
      deleted : {1: false, 2: true, 3: false, 4: false}
    });
    console.log(this);*/
    console.log(index);
  };

  render () {
    const mychips = Chiplist.map((chip, index) =>
      this.state.deleted[index] ? null : ( <Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>{chip.title}</Chip> )
    );
    return (
      <div className="chips-list">
        { mychips }
      </div>
    );
  }
}

export default ChipsList;

为什么,当我想将索引值传递给函数时,函数一直被调用,我不知道为什么...

因为您正在调用函数:

<Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>

传递函数的正确方法是不调用它,即:

<Chip deletable onDeleteClick={this.handleDeleteClick}>

但是,由于您需要索引,因此需要以某种方式保存它。输入 closures。你需要做的是有一个函数,returns一个函数,像这样:

handleDeleteClick(index) {
  return () => {
    console.log(index);
  }
};

然后,您可以使用您原来的方法创建芯片:

<Chip deletable onDeleteClick={this.handleDeleteClick(index + 1)}>