【问题标题】:React Hoc function return classReact Hoc 函数返回类
【发布时间】:2021-06-02 10:26:19
【问题描述】:

函数作为 React 子级无效。如果您从渲染返回一个组件而不是 <Component />,则可能会发生这种情况。或者,也许您打算调用这个函数而不是返回它。

import './App.css';
import React, { Component } from 'react';
const OOO = () => {

    //console.log(this.props.children)
    return class extends Component {
        render() {
            return (
                <Rem {...this.props} />
            );
        }
    }
}

class Rem extends Component {
    render() {
        return (
            <p>Helo</p>
        )
    }
}

export default OOO;

【问题讨论】:

    标签: reactjs higher-order-components


    【解决方案1】:

    如果您从渲染返回一个组件而不是 &lt;Component /&gt;,则可能会发生这种情况

    这正是您在这里所做的。调用 &lt;OOO /&gt; 返回 class 而不是 JSX 元素。

    这并不是真正的高阶组件,因为您没有将内部组件 Rem 作为参数。你打算吗?看起来像这样:

    const withOOO = (InnerComponent) => {
    
        return class extends Component {
            render() {
                return (
                    <InnerComponent {...this.props} />
                );
            }
        }
    }
    
    class Rem extends Component { ... }
    
    export default withOOO(Rem);
    

    如果这只是一个使用Rem的组件,而不是HOC,那么你不需要创建一个新类。

    const OOO = (props) => {
      return <Rem {...props} />;
    };
    
    class Rem extends Component { ... }
    
    export default OOO;
    

    【讨论】:

    • 感谢您的帮助!)
    【解决方案2】:

    我认为你用错了函数,函数OOO返回一个类,你可以使用那个类。我不知道你为什么要这样做,但这里是你如何使用 HOC:

    //your code in a file called OOO.js
    import React, { Component } from 'react';
    const OOO = () => {
      //you cannot log this.props here, it is not in the class
      //console.log(this.props.children)
      //I think you have to name the class but I'm not sure
      //Have not used classes in React for quite some time
      //even React documentation lists a large amount of
      //disadvantages using classes and it's only around for
      //legacy code
      return class MyComponent extends Component {
        render() {
          //here you can log this.props
          //console.log(this.props.children)
          return <Rem {...this.props} />;
        }
      };
    };
    
    class Rem extends Component {
      render() {
        return <p>Helo</p>;
      }
    }
    
    export default OOO;
    //end of the OOO.js file
    
    //here is how you can use it
    import CreateComponent from 'OOO.js';
    const Component = CreateComponent();
    const MyComponent = ()=><Component />
    export default MyComponent;
    

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 2018-01-30
      • 2021-03-10
      • 2022-01-18
      • 2021-05-15
      • 2017-10-05
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多