在这里遗漏了一些明显的东西。我为以下HOC获得Invariant Violation: Element type is invalid
:
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'.
答案 0 :(得分:1)
在React中区分组件和元素非常重要:
const MyComponent = () => <span /> // Component
const myElement = <MyComponent /> // Element
所以你的HOC接受Component,但你将元素传递给它:ButtonWithComponent(<Icon/>)
您有两种选择:
将组件传递给ButtonWithComponent
重构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>;