reactjs - 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'.
解决方案
在 React 中区分组件和元素很重要:
const MyComponent = () => <span /> // Component
const myElement = <MyComponent /> // Element
所以你的 HOC 接受组件,但你将元素传递给它: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>;
推荐阅读
- python - 如何使用 python 编写一个在几周而不是几秒(四个星期、十一个星期和十二个星期)内安排工作的代码
- google-bigquery - 如何进行 bigquery 传输:数据集投影
- swift - 给出一个自然正的 Int (n) 和一个期望的总和 (k) 找到一个长度为 n 且总和为 k 的随机数组
- r - GPS 热图与 ggplot (geom_Path)
- javascript - 如何在此函数之前返回带有美元符号的函数。(Javascript)
- java - Angular 8删除方法没有调用spring boot删除方法
- ios - Objective-c 非圆弧对象
- r - 安装 R 包时出错:使用 Anaconda 进行 scran
- excel - 如何将带有图像的表格从网页导入电子表格?
- python - 如何在 Python 3.7 中快速并行化函数?