如何在需要另一个 hoc 的反应中编写 HOC?

How to write a HOC in react which takes another hoc?

我正在自己学习资料 UI 并且遇到了这个 HOC 模式方法 withStyle HOC API,我尝试自己用简单的样式(只是字符串)实现来理解这个 hoc(withStyle ) 函数采用此 hoc(名为 HigherOrderComponent)函数在代码中工作。
这是 App.js 并在 index.js

中渲染<App/>
import React from 'react';
import customWithStyle  from './customWithStyle';
import Button from '@material-ui/core/Button';


function HigherOrderComponent(props) {

  return <Button color={props}>Higher-order component</Button>;

}


const someStyle="primary";
export default customWithStyle(someStyle)(HigherOrderComponent);

我尝试编写的代码在 customWithStyle.js 文件中

 import React from 'react'
 const customWithStyle=(style)=>(Hoc)=>{
          //console.log(style);
         console.log(<Hoc/>)
         return  <Hoc props={style}/>
 }


export default customWithStyle ;

我遇到错误

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

谁能帮忙。

在您的 HigherOrderComponent 功能组件中使用 props.props 作为 Button Material 组件中颜色属性的值

我使用 Hoc 的唯一方法是 class。这样的事情会对你有所帮助

function HigherOrderComponent(props) {
   return (<div style={{color: props.color}}>this is the main component</div>)
}

const customWithStyle = style => WrappedComponent => {
 class HOC extends React.Component{
       render = () => (<WrappedComponent color={style}></WrappedComponent>);
        }
  
 return HOC;
};

const StyledComponent = customWithStyle("red")(HigherOrderComponent);

ReactDOM.render(<StyledComponent />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>