我怎么能从 getCellActions 改变我的状态

How could i change my state from getCellActions

我是 React 新手。对于我的项目,我想通过单击 table 中的图标来更改我的状态,这将更改我的状态。我正在使用 getCellActions(反应数据网格)。我怎样才能将我的自定义函数与列和行对象单独传递。

提前致谢。

NT:我没有使用 redux

getCellActions(column, row, state) {

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

        }
    }

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

将您的 getCellActions 函数更改为 arrow function,这样您就可以将组件作为上下文(在箭头函数内,这会保留其原始上下文中的含义):

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

你可以简单地使用 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)}

你实际上传递了一个匿名函数,它只会在被触发时执行。 我想补充一点,当你在一行中写一个箭头函数时,它会自动 return 那个语句,除非你把那行用花括号括起来并写一个普通函数。所以,上面的行是:

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

所以,真言是:return参考,触发前不要执行。