React:动态表生成的bind方法

时间:2019-05-08 10:19:30

标签: javascript reactjs

我目前正在尝试生成一个表,该表不仅可以显示尽可能动态的值,而且还具有可以传递给特定列的功能。结构的草稿如下:

<Table
      dataHeaders={[
        { headerTitle: 'ID', headerKey: 'id', filterable: true },
        { headerTitle: 'First Name', headerKey: 'firstname', filterable: true, sortable: true },
        { headerTitle: 'Last Name', headerKey: 'lastname', filterable: true, sortable: true },
        {
          headerTitle: 'Details',
          text: 'Show details',
          functionalColumn: true,
          function: row => {
            alert(`${row.id}: ${row.firstname} ${row.middlename} ${row.lastname}`);
          },
        },
        {
          headerTitle: 'Delete',
          text: 'Delete',
          functionalColumn: true,
          function: row => {
            const remainingData = this.state.data.filter(item => item.id !== row.id);
            this.setState({ data: remainingData });
          },
        },
      ]}
      data={[
        { id: 1, firstname: 'Jess', lastname: 'Smith' },
        { id: 2, firstname: 'Alex', lastname: 'Williams' },
        { id: 3, firstname: 'Tayler', lastname: 'Brown' },
        { id: 4, firstname: 'Hannah', lastname: 'Anderson' },
        { id: 5, firstname: 'Anna', lastname: 'Adams' },
        { id: 6, firstname: 'Michael', lastname: 'Johnson' },
        { id: 7, firstname: 'John', lastname: 'Willis' },
        { id: 8, firstname: 'Joey', lastname: 'Sullivan' },
        { id: 9, firstname: 'Chandler', lastname: 'Anderson' },
        { id: 10, firstname: 'Monica', lastname: 'Black' },
        { id: 11, firstname: 'Rachel', lastname: 'Tyson' },
        { id: 12, firstname: 'Alex', lastname: 'Doe' },
      ]}
    />

使用Table组件中的代码,显示细节完全可以正常工作

<td key={`${metaColumn.text}-${index}`}>
   <span className={'Table__delete'} onClick={metaColumn.function.bind(this, row)}>
        {metaColumn.text}
   </span>
</td>

但是,毫不奇怪,操纵state的{​​{1}}不能正常工作,因为显然将方法与Table绑定是不够的。

在这种环境下是否可以使bind(this, row)可以访问?

1 个答案:

答案 0 :(得分:1)

所以,我终于弄清楚了为什么它不起作用。原因很简单:you cannot change the context of this in arrow functions

所以不是

function: row => {
    const remainingData = this.state.data.filter(item => item.id !== row.id);
    this.setState({ data: remainingData });
}

我用过:

function(row) {
    const remainingData = this.state.data.filter(item => item.id !== row.id);
    this.setState({ data: remainingData });
}