2

我是新来的反应。对于我的项目,我想通过单击表格中的图标来更改我的状态,这将改变我的状态。我正在使用 getCellActions (react-data-grid)。如何将我的自定义函数单独与列和行对象一起传递。

提前致谢。

NT:我没有使用 redux

getCellActions(column, row, state) {

        if(column.key === 'modify'){
            return [
                {
                    icon: 'fa fa-edit',
                    callback: () => {
                        console.log(row.id);
                       //this.getRoleData();
                    }
                }
            ];

        }
    }
4

2 回答 2

3

您可以简单地使用 ES6 并传递一个箭头函数表达式,该表达式简单地调用您想要的函数并this自动绑定该函数。

在 react-data-grid 中,您必须执行以下操作:

<ReactDataGrid
    columns={this._columns}
    rowGetter={this.rowGetter}
    rowsCount={this._rows.length}
    minHeight={300}
    getCellActions= {(column, row) => this.getCellActions(column, row)}
    state = {this.state}
/>

你的getCellActions功能可以是:

getCellActions(column, row) {

    if(column.key === 'modify'){
        return [
            {
                icon: 'fa fa-edit',
                callback: () => this.getRoleData(row.id)
            }
        ];

    }
}

问题是当你写:

getCellActions= {(column,row) => this.getCellActions(column, row)}

您实际上传递了一个仅在触发时才会执行的匿名函数。我想补充一点,当您在一行中编写箭头函数时,它会自动返回该语句,除非您将该行包裹在花括号中并编写一个普通函数。因此,上面的行作为:

getCellActions= {(column,row) => return this.getCellActions(column, row)}

所以,MANTRA 是:返回引用,不要在触发之前执行它。

于 2018-08-27T19:38:04.260 回答
2

为什么this.getRoleData()不起作用的问题是因为this您的回调内部不在您的组件的上下文中。

将您的getCellActions函数更改为箭头函数,因此您将组件作为上下文(在箭头函数内部,它的含义与其原始上下文保持一致):

import React from 'react';

class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedRowId: null
        };
    }

    myCallback = (rowId) => {
        console.log(rowId);
        this.setState({ selectedRowId: rowId });
    };

    getCellActions = (column, row, state) => {

        if(column.key === 'modify'){
            return [
                {
                    icon: 'fa fa-edit',
                    callback: () => {
                        console.log(row.id);
                        this.myCallback(row.id);
                    }
                }
            ];

        }
    }

    render() {
        // your render function...
    }
}

选择:

在构造函数中绑定this到:getCellActions

this.getCellActions = this.getCellActions.bind(this);
于 2018-08-27T14:56:26.297 回答