如何在javascript函数中访问多个上下文(React.Componentclass方法)

How to access multiple contexts in javascript function (React.Component class method)

我有 React 组件,它呈现第 3 方 HoC HotTableHotTable 上面有方法 afterValidate

我正在将 handleAfterValidate 函数传递给 HotTable。 问题是 handleAfterValidate 应该可以访问 HotTable 实例,同时可以访问 HotTableWrapper 实例(见下面的代码)。

默认handleAfterValidate里面的this是指HotTable实例。 如果我将处理程序绑定到 React 实例,那么我将失去对 HotTable 实例的访问权限,但我需要它们。

在这种情况下是否可以访问两个上下文?

class HotTableWrapper extends React.Component {
processCell(row, col) {
    // do something
}

handleAfterValidate(row, prop) {
    const col = this.propToCol(prop); // 'this' should refer to HotTable instance 
    this.processCell(row, col); // 'this' should refer to HotTableWrapper class instance
}

render() {
    return (
        <div>
            <HotTable afterValidate={this.handleAfterValidate} />
        </div>
    );
}

}

您可以使用柯里化函数方法。如果你有 lodash,那么你可以这样做:

class HotTableWrapper extends React.Component {
    processCell(row, col) {
        // do something
    }

    handleAfterValidate(wrapper, row, prop) {
        const col = this.propToCol(prop); // 'this' should refer to HotTable instance 
        wrapper.processCell(row, col); // 'this' should refer to HotTableWrapper class instance
    }

    render() {
        return (
            <div>
                <HotTable afterValidate={_.curry(this.handleAfterValidate)(this)} />
            </div>
        );
    }
}

https://lodash.com/docs/4.17.4#curry 如果您没有 lodash,只需 google 了解如何实现柯里化助手。

一种方法是直接在 HotTable 组件中定义 handleAfterValidate 代码,并将 processCell 作为范围为 HotTableWrapper 的道具传递。

所以在 HotTable 你会

handleAfterValidate(wrapper, row, prop) {
    const col = this.propToCol(prop);
    this.props.processCell(row, col);
}

并在 HotTableWrapper 渲染方法中

<HotTable processCell={this.processCell.bind(this)}/>