UNPKG

@ray-js/smart-ui

Version:

轻量、可靠的智能小程序 UI 组件库

64 lines (63 loc) 3.04 kB
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime"; import React from 'react'; import { isObject, mapKeys, omit, kebabCase } from 'lodash-es'; const styleObj2Str = (style) => { if (!isObject(style)) return style; return Object.entries(style).reduce((acc, [key, value]) => { return `${acc}${key}: ${value};`; }, ''); }; export const withReactProps = (WrappedComponent) => { return (props) => { var _a; // 自身是否是一个 Slot 组件 const isSelfSlot = typeof (props === null || props === void 0 ? void 0 : props.slot) === 'string'; const slotProps = isSelfSlot ? {} : (_a = props === null || props === void 0 ? void 0 : props.slot) !== null && _a !== void 0 ? _a : {}; const slotPropsNames = Object.keys(slotProps); const omitPropKeys = ['className', 'slot', 'children']; const stylePropsKeys = []; let vantProps = omit(props, omitPropKeys); vantProps = mapKeys(vantProps, (__, key) => { /** * React 中为 onClick,小程序中的 Event 标准写法为 bind:click,故这里会转一道 */ if (key.startsWith('on')) { const eventKey = `bind:${kebabCase(key.slice(2))}`; return eventKey; } if (key.endsWith('Style')) { const stylePropKey = kebabCase(key); stylePropsKeys.push(stylePropKey); return stylePropKey; } /** * React 为 camelCase,Smart 中的 props 统一为 kebab-case,故这里会转一道 */ return kebabCase(key); }); /** * React 中为 className,Smart 中使用 class,故这里会转一道 */ if (props.className) { vantProps.class = props.className; } if ((stylePropsKeys === null || stylePropsKeys === void 0 ? void 0 : stylePropsKeys.length) > 0) { stylePropsKeys.forEach(stylePropKey => { const stylePropValue = vantProps[stylePropKey]; vantProps[stylePropKey] = styleObj2Str(stylePropValue); }); } /** * 小程序中的 Slot 写法为子组件 + slot 属性,在 React 中无法直接使用,故这里会转一道, * 统一通过 slot props 来定义 */ if ((slotPropsNames === null || slotPropsNames === void 0 ? void 0 : slotPropsNames.length) > 0) { return (_jsxs(WrappedComponent, Object.assign({}, vantProps, { children: [slotPropsNames.map(slotName => { const name = kebabCase(slotName); return React.cloneElement(slotProps === null || slotProps === void 0 ? void 0 : slotProps[slotName], { key: slotName, slot: name }); }), props.children] }))); } return (_jsx(WrappedComponent, Object.assign({}, (isSelfSlot ? { slot: props.slot } : {}), vantProps, { children: props.children }))); }; };