|
| 1 | +import React from 'react'; |
| 2 | +import {findDomCompat} from './utils/findDomCompat'; |
| 3 | + |
| 4 | +interface TaggerWrapperProps { |
| 5 | + children: React.ReactElement; |
| 6 | + tagger: { |
| 7 | + [propName: string]: string | number; |
| 8 | + }; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * 自动给组件对应 dom 打标记,开发态时才会进来 |
| 13 | + * @param param0 |
| 14 | + * @returns |
| 15 | + */ |
| 16 | +export const TaggerWrapper: React.FC<TaggerWrapperProps> = ({ |
| 17 | + children, |
| 18 | + tagger |
| 19 | +}) => { |
| 20 | + const ref = React.useRef<HTMLElement | null>(null); |
| 21 | + |
| 22 | + React.useLayoutEffect(() => { |
| 23 | + if (!ref.current || !tagger) { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + const dom = findDomCompat(ref.current); |
| 28 | + const attrs: any = {}; |
| 29 | + Object.keys(tagger).forEach(key => { |
| 30 | + if (typeof tagger[key] === 'string' || typeof tagger[key] === 'number') { |
| 31 | + attrs[`data-amis-tagger-${key}`] = String(tagger[key]); |
| 32 | + } |
| 33 | + }); |
| 34 | + |
| 35 | + Object.keys(attrs).forEach(key => { |
| 36 | + dom?.setAttribute(key, attrs[key]); |
| 37 | + }); |
| 38 | + |
| 39 | + return () => { |
| 40 | + Object.keys(attrs).forEach(key => { |
| 41 | + dom?.removeAttribute(key); |
| 42 | + }); |
| 43 | + }; |
| 44 | + }, [tagger, ref.current]); |
| 45 | + |
| 46 | + // 合并 ref:保持原有 ref,同时添加我们的 ref |
| 47 | + const mergedRef = React.useCallback( |
| 48 | + (node: HTMLElement | null) => { |
| 49 | + ref.current = node; |
| 50 | + |
| 51 | + // 如果原有 children 有 ref,也调用它 |
| 52 | + const childRef = (children as any).ref; |
| 53 | + if (childRef) { |
| 54 | + if (typeof childRef === 'function') { |
| 55 | + childRef(node); |
| 56 | + } else { |
| 57 | + // ref 对象 |
| 58 | + childRef.current = node; |
| 59 | + } |
| 60 | + } |
| 61 | + }, |
| 62 | + [children] |
| 63 | + ); |
| 64 | + |
| 65 | + return React.cloneElement(children, { |
| 66 | + ref: mergedRef |
| 67 | + } as any); |
| 68 | +}; |
| 69 | + |
| 70 | +export default TaggerWrapper; |
0 commit comments