如何将 class 包装在高阶组件中?
How to wrap a class in a higher order component?
我想知道我是否可以将 class 组件包装在一个也有 class.
的 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,现在我正在传递一个 class 组件,如下所示:
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`
有可能吗?
谢谢!
想通了。
我在进口
import { Toast } from "react-native-easy-toast";
代替
import Toast from "react-native-easy-toast";
我想知道我是否可以将 class 组件包装在一个也有 class.
的 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,现在我正在传递一个 class 组件,如下所示:
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`
有可能吗?
谢谢!
想通了。
我在进口
import { Toast } from "react-native-easy-toast";
代替
import Toast from "react-native-easy-toast";