高阶组件
什么是高阶组件???
高阶组件就是一个函数,且该函数接受一个组件作为参数,并返回一个新的组件。基本上,这是从React的组成性质派生的一种模式,我们称它们为 “纯”组件, 因为它们可以接受任何动态提供的子组件,但它们不会修改或复制其输入组件的任何行为。
const EnhancedComponent = higherOrderComponent(WrappedComponent);
- 高阶组件(HOC)是 React 中用于复用组件逻辑的一种高级技巧
- 高阶组件的参数为一个组件返回一个新的组件
- 组件是将 props 转换为 UI,而高阶组件是将组件转换为另一个组件
以下封装了几个高阶组件.
1.react 路由懒加载
import React, {PureComponent} from "react";
export default function LoadAble(component) {
return class extends PureComponent {
state = {
Template: null
};
render() {
const {Template} = this.state;
{
return !Template ? null : <Template {...this.props}/>
}
}
async componentDidMount() {
let module = await component();
this.setState({
Template: module.default
})
}
}
}
2.react 滚动事件
import React, { Component } from 'react';
// import cssModuleHandler from "../../../utils/cssModuleHandler";
// import styleObject from './LoadMore.scss';
// const GSV = cssModuleHandler(styleObject);
class LoadMore extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const loadMoreFn = this.props.loadMoreFn;
const callback = () => {
if (this.getScrollTop() + this.getWindowHeight() + 100 > this.getScrollHeight()) {
loadMoreFn();
}
}
//滚动事件
let timeAction;
window.addEventListener('scroll', () => {
if (this.props.isLoadingMore) {
return;
}
if (timeAction) {
clearTimeout(timeAction);
}
timeAction = setTimeout(callback, 50);
});
}
//滚动条在Y轴上的滚动距离
getScrollTop() {
let scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if (document.body) {
bodyScrollTop = document.body.scrollTop;
}
if (document.documentElement) {
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//文档的总高度
getScrollHeight() {
let scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if (document.body) {
bodyScrollHeight = document.body.scrollHeight;
}
if (document.documentElement) {
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
//浏览器视口的高度
getWindowHeight() {
let windowHeight = 0;
if (document.compatMode == "CSS1Compat") {
windowHeight = document.documentElement.clientHeight;
} else {
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
render() {
let { isLoadingMore,itemImg } = this.props
// console.log(itemImg.images,"----");
return (
<React.Fragment>
{isLoadingMore
? <div className='loadMore' ref='wrapper'>
<img src={itemImg.images} alt="" />
</div>
: ''}
</React.Fragment>
)
}
}
export default LoadMore;