【问题标题】:How to write a HOC in react which takes another hoc?如何在需要另一个 hoc 的反应中编写 HOC?
【发布时间】:2020-06-30 23:01:45
【问题描述】:

我自己学习材料 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.

有人可以帮忙吗。

【问题讨论】:

    标签: javascript reactjs material-ui higher-order-components


    【解决方案1】:

    我使用 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>

    【讨论】:

    • 非常感谢。在函数中返回 jsx 元素是不可能的,我觉得这是我们应该使用类的原因。
    【解决方案2】:

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

    【讨论】:

    • 谢谢回复,还是一样的错误。我们可以在 customWithStyle.js 本身中进行所有修改吗?
    • 能不能直接控制台下HigherOrderComponent功能组件的props?它会带来什么价值..
    • Object { "$$typeof": Symbol(react.element), type: HigherOrderComponent(props)
    • 在您可以在 jsx 中使用该 Hoc 作为函数之前创建的 Hoc。例如
      {HigherOrderComponent}
      它将起作用
    • 也许它的 HOF 不是你之前创建的 HOC。
    猜你喜欢
    • 2017-12-02
    • 2019-07-10
    • 2021-03-10
    • 2019-12-16
    • 2018-12-27
    • 2022-01-01
    • 2021-07-13
    • 2018-09-11
    • 2021-05-11
    相关资源
    最近更新 更多