高阶组件-React Native-不变违反错误

时间:2020-01-13 03:05:02

标签: reactjs react-native

我正在尝试在HOC项目中使用ReactNative。但是得到Invariant Violation Error。下面是代码示例:

IconComponent.js:返回默认组件。

export class IconComponent extends React.Component {
    render() {
        return (
            <Image
                source={...}
                style={...} />
        );
    }
}

HomeScreen.js::呈现主屏幕。在这里出现不变冲突错误

render() {
    return (
        <View>
            {
                this.getCustomizedIconComponent()
            }
            <SomeView />
        </View>
    );
}

getCustomizedIconComponent = () => {
    const CustomizedIconHOC = getCustomizedIcon(IconComponent, "Custom Text");
    return CustomizedIconHOC;
}

CustomizedIconHOC.js:返回自定义组件。

export const getCustomizedIcon = (Comp, customString) => {
    class HOC extends React.Component {
        render() {
            return (
                <View>
                    <AnotherCustomView label={customString}/>
                    <Comp />
                </View>
            );
        }
    }
    return HOC;
};

错误消息:

Invariant Violation: Element type is invalid: expected a string( for built-in components) or a class/function (for composite components) but got: object.

关于什么是问题以及如何解决的任何指示?!

1 个答案:

答案 0 :(得分:0)

您需要返回组件的实例

getCustomizedIconComponent = () => {
    const CustomizedIconHOC = getCustomizedIcon(IconComponent, "Custom Text");
    return <CustomizedIconHOC />;
}

render() {
    const CustomizedIcon = this.getCustomizedIconComponent()

    return (
        <View>
            <CustomizedIcon />
            <SomeView />
        </View>
    );
}

请注意,这样做会在每次重新渲染时创建一个新组件