React高阶组件(hooks写法)
1.新建高阶组件hoc.tsx
import React, { useState } from 'react';
export interface IHocProps {
hocId: string;
name?: string;
children?: any;
}
export const HOC_Wrapper = (Component: Function, type?: string) => {
return (props: IHocProps) => {
// 权鉴是否登录
const isAdmin = useState<boolean>(!!localStorage.getItem('token'));
return isAdmin ? (
<Component {...props} type={type}></Component>
) : (
<div>请登录查看</div>
);
};
};
2.使用
// 高阶组件第一个参数组件
const hoc: FunctionComponent<IProps> = (props) => {
useEffect(() => {
console.log('props >>> ', props);
}, []);
return (
<div>
<p>这是木偶组件里的内容</p>
{props.children}
</div>
);
};
// 声明高阶组件
const Hoc = HOC_Wrapper(hoc, 'GoodsList');
// 使用
<Hoc hocId="hocId" name="first_hoc">
<div>哈哈哈</div>
</Hoc>
vue 高阶组件
import { h } from 'vue'
import NotFindPage from '@/views/404.vue'
export const withComponent = (wrapper, requestFunc) => ({
data() {
return {
showText: ''
}
},
mounted() {
if (this.haveAuth()) {
const params = this.$refs.wrapped.requestParams;
this.request(params)
this.$refs.wrapped.$watch('requestParams', (newResParams) => {
this.request(newResParams)
}, { immediate: true })
}
},
components:{
NotFindPage
},
methods: {
request(params) {
requestFunc(params).then((res) => {
this.showText = 'request(' + res + ')';
})
},
haveAuth() {
return !!(localStorage.getItem('token'))
}
},
render() {
// 将 this.$slots 格式化为数组,因为 h 函数第三个参数是子节点,是一个数组
const scopedSlots = Object.keys(this.$slots).map(key => this.$slots[key]())
const args = {
...this.$props,
text: this.showText,
ref: 'wrapped',
attrs: this.$attrs
}
return this.haveAuth() ? h(wrapper, args, [...scopedSlots]) : h(NotFindPage,{})
}
})