【问题标题】:How to wrap a class in a higher order component?如何将类包装在高阶组件中?
【发布时间】:2019-09-24 15:36:25
【问题描述】:

我想知道是否可以将一个类组件包装在一个也有一个类的 hoc 中。

import React, { Component } from "react";
import { View } from "react-native";
import { Toast } from "react-native-easy-toast";
const withToast = EnhancedComponent => {
    return class HOC extends Component {
        render() {
            return (
                <View>
                    <EnhancedComponent {...this.props} toast={(message, duration) => this.toast.show(message, duration)} />
                    <Toast
                        ref={toast => {
                            this.toast = toast;
                        }}
                    />
                </View>
            );
        }
    };
};
export default withToast;

这是我正在使用的 hoc,现在我正在传递一个像这样的类组件:

import React, { Component } from "react";
import withToast from "../../hoc/withToast";
import Btn from "react-native-micro-animated-button";
class Login extends Component<Props> {
render() {
            return <Btn title="Login" onPress={() => this.props.toast("logged in")} />;
        }
    }
export default withToast(Login);

当我运行它时,我得到了这个错误:

Invariant Violation: Invariant Violation: Invariant Violation: Element type is invalid: expected a string 
(for built-in components) or a class/function (for composite components) but got: undefined. 
You likely forgot to export your component from the file it's defined in, or you might have 
mixed up default and named imports.
Check the render method of `HOC`

有可能吗?

谢谢!

【问题讨论】:

  • 请包含minimal reproducible example,包括导入语句和文件位置。
  • 你是如何使用高阶登录的??
  • @EmileBergeron 已编辑
  • @MohamedELAYADI 我不太明白你的问题。我正在尝试使用 withToast hoc 登录。
  • 仍然不是最小的。如果不能解决问题,请删除任何与吐司相关的内容。告诉我们你在哪里使用Login 组件。

标签: javascript reactjs typescript react-native react-hoc


【解决方案1】:

想通了。 我在进口 import { Toast } from "react-native-easy-toast"; 代替 import Toast from "react-native-easy-toast";

【讨论】:

    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多