【发布时间】:2018-10-12 07:09:52
【问题描述】:
我有一个包装服务调用的高阶函数。数据通过回调流式传输,我必须将其传递给包装的组件。我目前已经编写了下面的代码,其中孩子将 handleChange 分配给 HOC 传递的空对象。包装的组件是一个常规的 JS 网格,因此我必须调用 api 来添加数据,而不是将其作为道具传递。
有没有更清洁的方法?
function withSubscription(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
this.handler = {};
}
componentDidMount() {
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange(row) {
if (typeof this.handler.handleChange === "function") {
this.handler.handleChange(row);
}
}
render() {
return <WrappedComponent serviceHandler={this.handler} {...this.props} />;
}
};
}
class MyGrid extends React.Component {
constructor(props) {
super(props);
if (props.serviceHandler !== undefined) {
props.serviceHandler.handleChange = this.handleChange.bind(this);
}
this.onReady = this.onReady.bind(this);
}
onReady(evt) {
this.gridApi = evt.api;
}
handleChange(row) {
this.gridApi.addRow(row);
}
render() {
return <NonReactGrid onReady={this.onReady} />;
}
}
const GridWithSubscription = withSubscription(MyGrid);
【问题讨论】:
标签: reactjs higher-order-functions