小编典典

是否可以将作为 Prop 传入的组件呈现给高阶组件?

javascript

我正在努力增加我对高阶组件的了解。我想知道是否可以渲染一个“组件”,它作为道具传递给更高阶的组件“SuperCommentList”。据我所知,无法将组件呈现为“this.props.component”,甚至无法呈现为实例变量“this.WrappedComponent”。我知道这不遵循传统的 HOC 约定,但试图确定这是否可能。我收到以下错误。谁能建议我如何做到这一点?

警告:

警告:React.jsx: type is invalid – 期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但是得到:. 您是否不小心导出了 JSX 文字而不是组件?在应用程序

错误:

react-dom.development.js:28439 未捕获错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:对象。

检查App. 在 createFiberFromTypeAndProps (react-dom.development.js:28439:1) 在 createFiberFromElement (react-dom.development.js:28465:1) 在 reconcileSingleElement (react-dom.development.js:15750:1) 在 reconcileChildFibers (react- dom.development.js:15808:1) 在 reconcileChildren (react-dom.development.js:19167:1) 在 updateContextProvider (react-dom.development.js:21154:1) 在 beginWork (react-dom.development.js :21649:1) 在 HTMLUnknownElement.callCallback (react-dom.development.js:4164:1) 在 Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1) 在 invokeGuardedCallback (react-dom.development.js: 4277:1)

HOC 通话

import CommentList from "./CommentList";
import data from "../utils/data";
import modelClass from "../utils/Model";
import SuperCommentList  from "../utils/SuperCommentList";

const CommentListWithSubscription = withSubscription(CommentList, model.data);

function withSubscription(WrappedComponent, selectedData) {
  const color = { color: selectedData.color };
  return <SuperCommentList selectedData={selectedData} component={WrappedComponent} color={color}/>;
}

下面的 HOC 示例:

import React, {Component} from "react";

class SuperCommentList extends Component {

   WrappedComponent;
    constructor(props) {
      super(props);
      console.log("WithSubscription props:", props);
      this.handleChange = this.handleChange.bind(this);

      this.WrappedComponent = this.props.component;
      this.state = {
        data: this.props.selectedData,
      };
    }

    componentDidMount() {
      // ... that takes care of the subscription...
      this.handleChange();
    }

    handleChange() {
      this.setState({
        data: this.props.selectedData,
      });
    }

    render() {
      console.log("WithSubscription State Data:", this.state.data);
      return <this.WrappedComponent data={this.state.data} {...this.props.color}/>;
    }
  }

  export default SuperCommentList;

阅读 91

收藏
2022-07-26

共1个答案

小编典典

HOC 需要返回一个组件,而不是一个渲染的 DOM 节点。

所以将 HOC 更改为

function withSubscription(WrappedComponent, selectedData) {
  const color = { color: selectedData.color };

  return function ComponentWithSubscription() {
     return <SuperCommentList selectedData={selectedData} component={WrappedComponent} color={color} />;
  }
}
2022-07-26