【问题标题】:Higher Order Component - React Native - Invariant Violation Error高阶组件 - React Native - 不变违规错误
【发布时间】:2020-01-13 03:05:02
【问题描述】:

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

IconComponent.js:返回默认组件。

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

HomeScreen.js: 呈现主屏幕。这里得到Invariant Violation Error

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.

关于问题出在哪里以及如何解决的任何指示?!

【问题讨论】:

  • 没有关闭?
  • 这是一个错字。现已更正。
  • 你能把整个错误信息放上去吗?
  • 您的HomeScreen.jsrender 应该有一个包含您的UI 的return 语句。
  • 如果您能将所有相关代码放入问题中,我们将不胜感激。这无助于我们缩小问题的范围。

标签: reactjs react-native


【解决方案1】:

需要返回组件的实例

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

或者

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

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

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

【讨论】:

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