在反应中输出更高阶的组件

时间:2018-05-20 09:42:39

标签: javascript reactjs

我有一个以下加载组件,它是一个HOC

renderer: function(value, meta) {
    meta.style = "background-color:lightgray;";
}

我在我的import React, { Component } from "react"; const isEmpty = prop => prop === null || prop === undefined || (prop.hasOwnProperty("length") && prop.length === 0) || (prop.constructor === Object && Object.keys(prop).length === 0); const LoadingHOC = loadingProp => WrappedComponent => { return class LoadingHOC extends Component { componentDidMount() { this.startTimer = Date.now(); } componentWillUpdate(nextProps) { if (!isEmpty(nextProps[loadingProp])) { this.endTimer = Date.now(); } } render() { const myProps = { loadingTime: ((this.endTimer - this.startTimer) / 1000).toFixed(2) }; return isEmpty(this.props[loadingProp]) ? ( <div className="loader" /> ) : ( <WrappedComponent {...this.props} {...myProps} /> ); } }; }; export default LoadingHOC; 组件中使用它来产生加载效果。

Feed组件是:

Feed

我使用import React, { Component } from "react"; import FeedItem from "./FeedItem"; import LoadingHOC from "./HOC/LoadingHOC"; class Feed extends Component { state = { filterText: "" }; render() { const { loadingTime } = this.props; return ( <div className="feed"> <FeedItem contacts={this.props.contacts} filterText={this.state.filterText} /> {/* <p>Loading time {loadingTime} seconds</p> */} </div> ); } } export default LoadingHOC("contacts", Feed); 中的Feed组件,例如App.js

但是我收到以下错误 - <Feed contacts={this.state.contacts} />

据我所知,这是因为没有正确调用HOC。但是我在Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.中做错了什么?

1 个答案:

答案 0 :(得分:5)

您的HOC是curried功能。所以你需要打两次电话

export default LoadingHOC("contacts")(Feed);