From 2efb5810c06d9ee0e6f378d97c6b74a492c36714 Mon Sep 17 00:00:00 2001 From: lio-mengxiang <1334196450@qq.com> Date: Mon, 7 Mar 2022 22:09:34 +0800 Subject: [PATCH] fix: (Typography) renderCopy function has bug when child element is react node --- packages/semi-ui/typography/base.tsx | 24 ++---------------------- packages/semi-ui/typography/util.tsx | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/packages/semi-ui/typography/base.tsx b/packages/semi-ui/typography/base.tsx index 078aabead2..fb95b4c539 100644 --- a/packages/semi-ui/typography/base.tsx +++ b/packages/semi-ui/typography/base.tsx @@ -9,7 +9,7 @@ import { IconSize as Size } from '../icons/index'; import { isUndefined, omit, merge, isString } from 'lodash'; import Tooltip from '../tooltip/index'; import Popover from '../popover/index'; -import getRenderText from './util'; +import getRenderText, { mergedToString } from './util'; import warning from '@douyinfe/semi-foundation/utils/warning'; import isEnterPress from '@douyinfe/semi-foundation/utils/isEnterPress'; import LocaleConsumer from '../locale/localeConsumer'; @@ -490,27 +490,7 @@ export default class Base extends Component { - if (typeof value === 'object') { - hasObject = true; - } - copyContent += String(value); - }); - } else if (typeof children !== 'object') { - copyContent = String(children); - } else { - hasObject = true; - copyContent = String(children); - } - - warning( - hasObject, - 'Children in Typography is a object, it will case a [object Object] mistake when copy to clipboard.' - ); + const copyContent: string = mergedToString(children); const copyConfig = { content: copyContent, duration: 3, diff --git a/packages/semi-ui/typography/util.tsx b/packages/semi-ui/typography/util.tsx index bcea5b880e..085b9b4987 100644 --- a/packages/semi-ui/typography/util.tsx +++ b/packages/semi-ui/typography/util.tsx @@ -1,5 +1,6 @@ import ReactDOM from 'react-dom'; import React from 'react'; +import { isString, isNumber } from 'lodash'; /** * The logic of JS for text truncation is referenced from antd typography @@ -137,4 +138,25 @@ const getRenderText = ( return resText; }; +const isSingleNode = (child: React.ReactNode) => { + return isString(child) || isNumber(child); +}; + + +export function mergedToString(children: any): string { + const mergedResult = ['']; + React.Children.forEach(children, (child) => { + const prevIndex = mergedResult.length - 1; + const prevChild = mergedResult[prevIndex]; + + if (isSingleNode(child) && isSingleNode(prevChild)) { + mergedResult[prevIndex] = `${prevChild}${child}`; + } else if (child?.props?.children) { + mergedResult.push(mergedToString(child.props.children)); + } + }); + + return mergedResult.join(''); +} + export default getRenderText; \ No newline at end of file