簡體   English   中英

如何在需要另一個 hoc 的 React 中編寫 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/> this

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.

有人可以幫忙嗎?

我使用 Hoc 的唯一方法是上課。 像這樣的東西會幫助你

 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>

在您的 HigherOrderComponent 功能組件中使用 props.props 作為按鈕材料組件中顏色屬性的值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM