企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 高阶组件 > 具体而言,高阶组件就是一个函数,且该函数接受一个组件作为参数,并返回一个新的组件。 > ~~~ function withSubscription(WrappedComponent, selectData) { // ……返回另一个新组件…… return class extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { data: selectData(DataSource, props) }; } componentDidMount() { // ……注意订阅数据…… DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { DataSource.removeChangeListener(this.handleChange); } handleChange() { this.setState({ data: selectData(DataSource, this.props) }); } render() { // ……使用最新的数据渲染组件 // 注意此处将已有的props属性传递给原组件 return <WrappedComponent data={this.state.data} {...this.props} />; } }; } ~~~