【问题标题】:"Functions are not valid as a React child" when trying to use HOC from a module object尝试从模块对象中使用 HOC 时,“函数作为 React 子项无效”
【发布时间】:2019-06-08 15:48:17
【问题描述】:

请参阅下面的代码,我正在尝试使用从 IIFE 返回的模块对象中的“HOC”,以使事情变得简单,我将大部分代码保留在 HTML 文件中。但是我得到了“警告”(或者真的是“错误”,因为我的页面不会呈现):“函数作为 React 子级无效。”

我尝试了一些不起作用的方法,首先将 () 添加到 withFoobar.HOC(Salutation)() 的末尾,这与此处建议的 (https://stackoverflow.com/a/51220156/34806) 不同,但这会导致“未捕获的类型错误:无法调用类作为函数”,这很有意义。我也尝试过在 return 之前添加,但这只会导致语法错误。

没有模块对象,我的代码主要基于以下要点:https://gist.github.com/sebmarkbage/ef0bf1f338a7182b6775 但我希望能够接受除了组件之外的参数,然后将它们存储起来以供将来参考。我正在尝试的可能吗?谢谢。

const withFooBar = (() => {
    let params;

    return {
        HOC: (ComponentWithFooBar, param) => class extends React.Component {
            constructor(props) {
              super(props);
              this.state = { data: null };
              params = params || [];
              params.push(param);
            }
            render() {
                return <ComponentWithFooBar {...this.props} data={this.state.data} />;
            }
        },
        getParams: {
            return params;
        }
    }
})();

ReactDOM.render(
    //<Salutation />,
    withFooBar.HOC(Salutation),
    document.getElementById('app-content')
);

【问题讨论】:

    标签: javascript reactjs module


    【解决方案1】:

    高阶组件返回一个组件。 render 期望 React element 而不是 component 作为第一个参数。应该是:

    const SalutationWithFooBar = withFooBar.HOC(Salutation);
    
    ReactDOM.render(
        <SalutationWithFooBar />,
        document.getElementById('app-content')
    );
    

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 2021-03-21
      • 2019-06-15
      • 1970-01-01
      • 2021-06-03
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多