为什么 "this" 的值保留在高阶组件中?

Why is the value of "this" preserved in Higher Order Components?

考虑以下高阶组件(来自 React 文档并 "simplified"):

function withSubscription(WrappedComponent, selectData) {
  return class extends React.Component {
    state = {
      data: selectData(DataSource, props)
    };

   componentDidMount() {
     DataSource.addChangeListener(this.handleChange);
   }

   componentWillUnmount() {
     DataSource.removeChangeListener(this.handleChange);
   }

   handleChange = () => {
     this.setState({ data: selectData(DataSource, this.props) });
   }

   render() {
     return <WrappedComponent data={this.state.data} {...this.props} />;
   }
 };
}

在render方法中,所有最初属于WrappedComponent的props都由{...this.props}传递。但是我仍然很难理解为什么会这样,因为(据我所知)新函数和 class 声明有它们自己的 this 值。这意味着 this 关键字应该(?)属于新返回的 class,但为什么没有发生这种情况?

“withSubscription”是“HOC 函数”,它将return 成为“HOC 增强组件”

EnhancedComponent = withSubscription(OriginalComponent);

为了使用,你会用他的道具调用EnhancedComponent。这里的“this”是EnhancedComponent的上下文“this”。例如:

<EnhancedComponent p1="test1" p2="test2"/>

所以在这种情况下,{...this.props} 是传递给 OriginalComponent 的 EnhancedComponent 的 p1、p2。