一 React 封装组件的一些心得( 二 )


// @import '../style/index.less';@class-prefix: ~'com-count';.@{class-prefix} {width: 100px;&-title {font-weight: bold;}&-count {color: skyblue;}}
该钩子是从 arco- 借鉴过来改进的 。

一  React 封装组件的一些心得

文章插图
import { useMemo } from 'react';import omit from '@/utils/omit';export type MergePropsOptions = {_ignorePropsFromGlobal?: boolean;};/** 将某些属性变为必选 */type RequireKey = Omit & { [P in K]-?: T[P] }export default function useMergeProps(componentProps: PropsType & MergePropsOptions,defaultProps: Partial,globalComponentConfig: Partial = {}): RequireKey {const { _ignorePropsFromGlobal } = componentProps;const _defaultProps = useMemo(() => {return { ...defaultProps, ...(_ignorePropsFromGlobal ? {} : globalComponentConfig) };}, [defaultProps, globalComponentConfig, _ignorePropsFromGlobal]);const props = useMemo(() => {const mProps = omit(componentProps, ['_ignorePropsFromGlobal']) as PropsType;for (const propName in _defaultProps) {if (mProps[propName] === undefined) {mProps[propName] = _defaultProps[propName]!;}}return mProps;}, [componentProps, _defaultProps]);return props as RequireKey;}
omit
/** 删除一个对象中的key */export default function omit(obj: T,keys: Array // string 为了某些没有声明的属性被omit): Omit {const clone = {...obj,};keys.forEach((key) => {if ((key as K) in clone) {delete clone[key as K];}});return clone;}
配置用户代码片段
一  React 封装组件的一些心得

文章插图
配置位置
一  React 封装组件的一些心得

文章插图
这里输入名称创建就可以了 。
一  React 封装组件的一些心得

文章插图
往里面加入以下 json 数据
"tsxcomreact": {"prefix": "tsxcomreact","body": ["import React, { useState, useEffect } from 'react';","import './index.less';","import { NativeProps, withNativeProps } from '@/utils/native-props````"import useMergeProps from '@/hooks/use-merge-props';","","const classPrefix = `com${2}-${1}`;","","export type ${1}Props = { ","","} & NativeProps","","const defaultProps = {","","}","type RequireType = keyof typeof defaultProps","","const ${1} = (comProps: ${1}Props) => {","const props = useMergeProps<${1}Props, RequireType>(comProps, defaultProps)","const { ...ret } = props","","return withNativeProps(","ret,","","","",")","}","","export default ${1}"],"description": "Log output to console"},"cdivclass": {"scope": "typescriptreact","prefix": "cdc","body": [""],"description": "Log output to console"},
结语
如果有大佬看到这里,希望能给点意见和改进方法 。