反应工具箱可删除芯片

时间:2017-06-07 14:55:02

标签: javascript reactjs react-toolbox

我尝试添加许多筹码(http://react-toolbox.com/#/components/chip)但我真的失败了React ......

链接中的示例仅显示单个可删除芯片。只要有一个可删除芯片,它就可以工作,但是我无法使用更多芯片。

这是我的代码:

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;

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

1 个答案:

答案 0 :(得分:0)

因为您正在调用该函数:

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

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

<Chip deletable onDeleteClick={this.handleDeleteClick}>

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

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

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

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