首页 > 解决方案 > React HOC 的不变违规

问题描述

这里遗漏了一些明显的东西。我正在获得Invariant Violation: Element type is invalid以下 HOC:

export const ButtonWithComponent = (Comp) => props =>
<TouchableOpacity
  onPress={props.onPress}
  style={{
    paddingHorizontal: 10,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center'
  }}
  hitSlop={{ left: 5, right: 5, top: 5, bottom: 5 }}
>
  <Comp />
</TouchableOpacity>;

使用如下:

const PencilButton = ButtonWithComponent(
    <Icon name="pencil" color={APP_MAIN_COLOR} size={30} type="entypo" />
);

class myClass extends Component {

...

render() {
    return (
        <PencilButton onPress={() => console.log('')} />
    );
}

}

我已经登录console.log(PencilButton)并看到了以 props 作为参数的预期无状态组件函数。我的导入如下:

import { ButtonWithComponent } from '../path/to/ButtonWithComponent.js'.

标签: reactjsreact-native

解决方案


在 React 中区分组件和元素很重要:

const MyComponent = () => <span /> // Component
const myElement = <MyComponent /> // Element

所以你的 HOC 接受组件,但你将元素传递给它:ButtonWithComponent(<Icon/>)

你有两个选择:

  1. 将组件传递给 ButtonWithComponent

  2. 重构 ButtonWithComponent 以接受元素:

    export const ButtonWithComponent = (children) => props =>
    <TouchableOpacity
      onPress={props.onPress}
      style={{
        paddingHorizontal: 10,
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center'
      }}
      hitSlop={{ left: 5, right: 5, top: 5, bottom: 5 }}
    >
       {children}
    </TouchableOpacity>;
    

推荐阅读