index.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /* eslint-disable prefer-destructuring, max-lines-per-function, react/no-find-dom-node, max-len, @typescript-eslint/no-empty-function */
  2. import React, { isValidElement, cloneElement } from 'react';
  3. import ReactDOM from 'react-dom';
  4. import classNames from 'classnames';
  5. import PropTypes from 'prop-types';
  6. import { throttle, noop, get, omit, each, isEmpty } from 'lodash-es';
  7. import { BASE_CLASS_PREFIX } from '@douyinfe/semi-foundation/base/constants';
  8. import warning from '@douyinfe/semi-foundation/utils/warning';
  9. import Event from '@douyinfe/semi-foundation/utils/Event';
  10. import { ArrayElement } from '@douyinfe/semi-foundation/utils/type';
  11. import { convertDOMRectToObject, DOMRectLikeType } from '@douyinfe/semi-foundation/utils/dom';
  12. import TooltipFoundation, { TooltipAdapter, Position, PopupContainerDOMRect } from '@douyinfe/semi-foundation/tooltip/foundation';
  13. import { strings, cssClasses, numbers } from '@douyinfe/semi-foundation/tooltip/constants';
  14. import '@douyinfe/semi-foundation/tooltip/tooltip.scss';
  15. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  16. import { isHTMLElement } from '../_base/reactUtils';
  17. import { stopPropagation } from '../_utils';
  18. import Portal from '../_portal/index';
  19. import ConfigContext from '../configProvider/context';
  20. import TriangleArrow from './TriangleArrow';
  21. import TriangleArrowVertical from './TriangleArrowVertical';
  22. import TooltipTransition from './TooltipStyledTransition';
  23. import ArrowBoundingShape from './ArrowBoundingShape';
  24. import { Motion } from '../_base/base';
  25. export { TooltipTransitionProps } from './TooltipStyledTransition';
  26. export type Trigger = ArrayElement<typeof strings.TRIGGER_SET>;
  27. export interface ArrowBounding {
  28. offsetX?: number;
  29. offsetY?: number;
  30. width?: number;
  31. height?: number;
  32. }
  33. export interface TooltipProps extends BaseProps {
  34. children?: React.ReactNode;
  35. motion?: Motion;
  36. autoAdjustOverflow?: boolean;
  37. position?: Position;
  38. getPopupContainer?: () => HTMLElement;
  39. mouseEnterDelay?: number;
  40. mouseLeaveDelay?: number;
  41. trigger?: Trigger;
  42. className?: string;
  43. clickToHide?: boolean;
  44. visible?: boolean;
  45. style?: React.CSSProperties;
  46. content?: React.ReactNode;
  47. prefixCls?: string;
  48. onVisibleChange?: (visible: boolean) => void;
  49. spacing?: number;
  50. showArrow?: boolean | React.ReactNode;
  51. zIndex?: number;
  52. rePosKey?: string | number;
  53. arrowBounding?: ArrowBounding;
  54. transformFromCenter?: boolean;
  55. arrowPointAtCenter?: boolean;
  56. wrapWhenSpecial?: boolean;
  57. stopPropagation?: boolean;
  58. clickTriggerToHide?: boolean;
  59. wrapperClassName?: string;
  60. }
  61. interface TooltipState {
  62. visible: boolean;
  63. transitionState: string;
  64. triggerEventSet: {
  65. [key: string]: any;
  66. };
  67. portalEventSet: {
  68. [key: string]: any;
  69. };
  70. containerStyle: React.CSSProperties;
  71. isInsert: boolean;
  72. placement: Position;
  73. transitionStyle: Record<string, any>;
  74. }
  75. const prefix = cssClasses.PREFIX;
  76. const positionSet = strings.POSITION_SET;
  77. const triggerSet = strings.TRIGGER_SET;
  78. const blockDisplays = ['flex', 'block', 'table', 'flow-root', 'grid'];
  79. const defaultGetContainer = () => document.body;
  80. export default class Tooltip extends BaseComponent<TooltipProps, TooltipState> {
  81. static contextType = ConfigContext;
  82. static propTypes = {
  83. children: PropTypes.node,
  84. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.object, PropTypes.func]),
  85. autoAdjustOverflow: PropTypes.bool,
  86. position: PropTypes.oneOf(positionSet),
  87. getPopupContainer: PropTypes.func,
  88. mouseEnterDelay: PropTypes.number,
  89. mouseLeaveDelay: PropTypes.number,
  90. trigger: PropTypes.oneOf(triggerSet).isRequired,
  91. className: PropTypes.string,
  92. wrapperClassName: PropTypes.string,
  93. clickToHide: PropTypes.bool,
  94. // used with trigger === hover, private
  95. clickTriggerToHide: PropTypes.bool,
  96. visible: PropTypes.bool,
  97. style: PropTypes.object,
  98. content: PropTypes.node,
  99. prefixCls: PropTypes.string,
  100. onVisibleChange: PropTypes.func,
  101. spacing: PropTypes.number,
  102. showArrow: PropTypes.oneOfType([PropTypes.bool, PropTypes.node]),
  103. zIndex: PropTypes.number,
  104. rePosKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  105. arrowBounding: ArrowBoundingShape,
  106. transformFromCenter: PropTypes.bool, // Whether to change from the center of the trigger (for dynamic effects)
  107. arrowPointAtCenter: PropTypes.bool,
  108. stopPropagation: PropTypes.bool,
  109. // private
  110. wrapWhenSpecial: PropTypes.bool, // when trigger has special status such as "disabled" or "loading", wrap span
  111. };
  112. static defaultProps = {
  113. transformFromCenter: true,
  114. arrowPointAtCenter: true,
  115. wrapWhenSpecial: true,
  116. motion: true,
  117. zIndex: numbers.DEFAULT_Z_INDEX,
  118. trigger: 'hover',
  119. position: 'top',
  120. prefixCls: prefix,
  121. autoAdjustOverflow: true,
  122. mouseEnterDelay: numbers.MOUSE_ENTER_DELAY,
  123. mouseLeaveDelay: numbers.MOUSE_LEAVE_DELAY,
  124. onVisibleChange: noop,
  125. spacing: numbers.SPACING,
  126. showArrow: true,
  127. arrowBounding: numbers.ARROW_BOUNDING,
  128. };
  129. eventManager: Event;
  130. triggerEl: React.RefObject<unknown>;
  131. containerEl: React.RefObject<unknown>;
  132. clickOutsideHandler: any;
  133. resizeHandler: any;
  134. isWrapped: boolean;
  135. mounted: any;
  136. scrollHandler: any;
  137. getPopupContainer: () => HTMLElement;
  138. containerPosition: string;
  139. constructor(props: TooltipProps) {
  140. super(props);
  141. this.state = {
  142. visible: false,
  143. /**
  144. *
  145. * Note: The transitionState parameter is equivalent to isInsert
  146. */
  147. transitionState: '',
  148. triggerEventSet: {},
  149. portalEventSet: {},
  150. containerStyle: {
  151. // zIndex: props.zIndex,
  152. },
  153. isInsert: false,
  154. placement: props.position || 'top',
  155. transitionStyle: {},
  156. };
  157. this.foundation = new TooltipFoundation(this.adapter);
  158. this.eventManager = new Event();
  159. this.triggerEl = React.createRef();
  160. this.containerEl = React.createRef();
  161. this.clickOutsideHandler = null;
  162. this.resizeHandler = null;
  163. this.isWrapped = false; // Identifies whether a span element is wrapped
  164. this.containerPosition = undefined;
  165. }
  166. setContainerEl = (node: HTMLDivElement) => (this.containerEl = { current: node });
  167. get adapter(): TooltipAdapter<TooltipProps, TooltipState> {
  168. return {
  169. ...super.adapter,
  170. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  171. // @ts-ignore
  172. on: (...args: any[]) => this.eventManager.on(...args),
  173. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  174. // @ts-ignore
  175. off: (...args: any[]) => this.eventManager.off(...args),
  176. insertPortal: (content: string, { position, ...containerStyle }: { position: Position }) => {
  177. this.setState(
  178. {
  179. isInsert: true,
  180. transitionState: 'enter',
  181. containerStyle: { ...this.state.containerStyle, ...containerStyle },
  182. },
  183. () => {
  184. /**
  185. * Dangerous: remove setTimeout from here fix #1301
  186. * setTimeout may emit portalInserted event after hiding portal
  187. * Hiding portal will remove portalInserted event listener(normal process)
  188. * then portal can't hide because _togglePortalVisible(false) will found isVisible=false and nowVisible=false(bug here)
  189. */
  190. this.eventManager.emit('portalInserted');
  191. }
  192. );
  193. },
  194. removePortal: () => {
  195. this.setState({ isInsert: false });
  196. },
  197. getEventName: () => ({
  198. mouseEnter: 'onMouseEnter',
  199. mouseLeave: 'onMouseLeave',
  200. mouseOut: 'onMouseOut',
  201. mouseOver: 'onMouseOver',
  202. click: 'onClick',
  203. focus: 'onFocus',
  204. blur: 'onBlur',
  205. }),
  206. registerTriggerEvent: (triggerEventSet: Record<string, any>) => {
  207. this.setState({ triggerEventSet });
  208. },
  209. unregisterTriggerEvent: () => {},
  210. registerPortalEvent: (portalEventSet: Record<string, any>) => {
  211. this.setState({ portalEventSet });
  212. },
  213. unregisterPortalEvent: () => {},
  214. getTriggerBounding: () => {
  215. // eslint-disable-next-line
  216. // It may be a React component or an html element
  217. // There is no guarantee that triggerE l.current can get the real dom, so call findDOMNode to ensure that you can get the real dom
  218. let triggerDOM = this.triggerEl.current;
  219. if (!isHTMLElement(this.triggerEl.current)) {
  220. const realDomNode = ReactDOM.findDOMNode(this.triggerEl.current as React.ReactInstance);
  221. (this.triggerEl as any).current = realDomNode;
  222. triggerDOM = realDomNode;
  223. }
  224. return triggerDOM && (triggerDOM as Element).getBoundingClientRect();
  225. },
  226. // Gets the outer size of the specified container
  227. getPopupContainerRect: () => {
  228. const container = this.getPopupContainer();
  229. let rect: PopupContainerDOMRect = null;
  230. if (container && isHTMLElement(container)) {
  231. const boundingRect: DOMRectLikeType = convertDOMRectToObject(container.getBoundingClientRect());
  232. rect = {
  233. ...boundingRect,
  234. scrollLeft: container.scrollLeft,
  235. scrollTop: container.scrollTop,
  236. };
  237. }
  238. return rect;
  239. },
  240. containerIsBody: () => {
  241. const container = this.getPopupContainer();
  242. return container === document.body;
  243. },
  244. containerIsRelative: () => {
  245. const container = this.getPopupContainer();
  246. const computedStyle = window.getComputedStyle(container);
  247. return computedStyle.getPropertyValue('position') === 'relative';
  248. },
  249. containerIsRelativeOrAbsolute: () => ['relative', 'absolute'].includes(this.containerPosition),
  250. // Get the size of the pop-up layer
  251. getWrapperBounding: () => {
  252. const el = this.containerEl && this.containerEl.current;
  253. return el && (el as Element).getBoundingClientRect();
  254. },
  255. getDocumentElementBounding: () => document.documentElement.getBoundingClientRect(),
  256. setPosition: ({ position, ...style }: { position: Position }) => {
  257. this.setState(
  258. { containerStyle: { ...this.state.containerStyle, ...style }, placement: position },
  259. () => {
  260. this.eventManager.emit('positionUpdated');
  261. }
  262. );
  263. },
  264. updatePlacementAttr: (placement: Position) => {
  265. this.setState({ placement });
  266. },
  267. togglePortalVisible: (visible: boolean, cb: () => void) => {
  268. const willUpdateStates: Partial<TooltipState> = {};
  269. if (this.adapter.canMotion()) {
  270. willUpdateStates.transitionState = visible ? 'enter' : 'leave';
  271. willUpdateStates.visible = visible;
  272. } else {
  273. willUpdateStates.visible = visible;
  274. }
  275. this.setState(willUpdateStates as TooltipState, () => {
  276. cb();
  277. });
  278. },
  279. registerClickOutsideHandler: (cb: () => void) => {
  280. if (this.clickOutsideHandler) {
  281. this.adapter.unregisterClickOutsideHandler();
  282. }
  283. this.clickOutsideHandler = (e: MouseEvent): any => {
  284. if (!this.mounted) {
  285. return false;
  286. }
  287. let el = this.triggerEl && this.triggerEl.current;
  288. let popupEl = this.containerEl && this.containerEl.current;
  289. el = ReactDOM.findDOMNode(el as React.ReactInstance);
  290. popupEl = ReactDOM.findDOMNode(popupEl as React.ReactInstance);
  291. if (
  292. (el && !(el as any).contains(e.target) && popupEl && !(popupEl as any).contains(e.target)) ||
  293. this.props.clickTriggerToHide
  294. ) {
  295. cb();
  296. }
  297. };
  298. document.addEventListener('click', this.clickOutsideHandler, false);
  299. },
  300. unregisterClickOutsideHandler: () => {
  301. if (this.clickOutsideHandler) {
  302. document.removeEventListener('click', this.clickOutsideHandler, false);
  303. this.clickOutsideHandler = null;
  304. }
  305. },
  306. registerResizeHandler: (cb: (e: any) => void) => {
  307. if (this.resizeHandler) {
  308. this.adapter.unregisterResizeHandler();
  309. }
  310. this.resizeHandler = throttle((e): any => {
  311. if (!this.mounted) {
  312. return false;
  313. }
  314. cb(e);
  315. }, 10);
  316. window.addEventListener('resize', this.resizeHandler, false);
  317. },
  318. unregisterResizeHandler: () => {
  319. if (this.resizeHandler) {
  320. window.removeEventListener('resize', this.resizeHandler, false);
  321. this.resizeHandler = null;
  322. }
  323. },
  324. notifyVisibleChange: (visible: boolean) => {
  325. this.props.onVisibleChange(visible);
  326. },
  327. registerScrollHandler: (rePositionCb: (arg: { x: number; y: number }) => void) => {
  328. if (this.scrollHandler) {
  329. this.adapter.unregisterScrollHandler();
  330. }
  331. this.scrollHandler = throttle((e): any => {
  332. if (!this.mounted) {
  333. return false;
  334. }
  335. let triggerDOM = this.triggerEl.current;
  336. if (!isHTMLElement(this.triggerEl.current)) {
  337. triggerDOM = ReactDOM.findDOMNode(this.triggerEl.current as React.ReactInstance);
  338. }
  339. const isRelativeScroll = e.target.contains(triggerDOM);
  340. if (isRelativeScroll) {
  341. const scrollPos = { x: e.target.scrollLeft, y: e.target.scrollTop };
  342. rePositionCb(scrollPos);
  343. }
  344. }, 10); // When it is greater than 16ms, it will be very obvious
  345. window.addEventListener('scroll', this.scrollHandler, true);
  346. },
  347. unregisterScrollHandler: () => {
  348. if (this.scrollHandler) {
  349. window.removeEventListener('scroll', this.scrollHandler, true);
  350. this.scrollHandler = null;
  351. }
  352. },
  353. canMotion: () => Boolean(this.props.motion),
  354. updateContainerPosition: () => {
  355. const container = this.getPopupContainer();
  356. if (container && isHTMLElement(container)) {
  357. // getComputedStyle need first parameter is Element type
  358. const computedStyle = window.getComputedStyle(container);
  359. const position = computedStyle.getPropertyValue('position');
  360. this.containerPosition = position;
  361. }
  362. },
  363. getContainerPosition: () => this.containerPosition,
  364. };
  365. }
  366. componentDidMount() {
  367. this.mounted = true;
  368. this.getPopupContainer = this.props.getPopupContainer || this.context.getPopupContainer || defaultGetContainer;
  369. this.foundation.init();
  370. }
  371. componentWillUnmount() {
  372. this.mounted = false;
  373. this.foundation.destroy();
  374. }
  375. isSpecial = (elem: React.ReactNode | HTMLElement | any) => {
  376. if (isHTMLElement(elem)) {
  377. return Boolean(elem.disabled);
  378. } else if (isValidElement(elem)) {
  379. const disabled = get(elem, 'props.disabled');
  380. if (disabled) {
  381. return strings.STATUS_DISABLED;
  382. }
  383. const loading = get(elem, 'props.loading');
  384. /* Only judge the loading state of the Button, and no longer judge other components */
  385. const isButton = !isEmpty(elem)
  386. && !isEmpty(elem.type)
  387. && (elem.type as any).name === 'Button'
  388. || (elem.type as any).name === 'IconButton';
  389. if (loading && isButton) {
  390. return strings.STATUS_LOADING;
  391. }
  392. }
  393. return false;
  394. };
  395. willEnter = () => {
  396. this.foundation.calcPosition();
  397. /**
  398. * Dangerous: remove setState in motion fix #1379
  399. * because togglePortalVisible callback function will use visible state to notifyVisibleChange
  400. * if visible state is old value, then notifyVisibleChange function will not be called
  401. * we should ensure that after calling togglePortalVisible, callback function can get right visible value
  402. */
  403. // this.setState({ visible: true });
  404. };
  405. didLeave = () => {
  406. this.adapter.unregisterClickOutsideHandler();
  407. this.adapter.unregisterScrollHandler();
  408. this.adapter.unregisterResizeHandler();
  409. this.adapter.removePortal();
  410. };
  411. /** for transition - end */
  412. rePosition() {
  413. return this.foundation.calcPosition();
  414. }
  415. componentDidUpdate(prevProps: TooltipProps, prevState: TooltipState) {
  416. warning(
  417. this.props.mouseLeaveDelay < this.props.mouseEnterDelay,
  418. "[Semi Tooltip] 'mouseLeaveDelay' cannot be less than 'mouseEnterDelay', which may cause the dropdown layer to not be hidden."
  419. );
  420. if (prevProps.visible !== this.props.visible) {
  421. this.props.visible ? this.foundation.delayShow() : this.foundation.delayHide();
  422. }
  423. if (prevProps.rePosKey !== this.props.rePosKey) {
  424. this.rePosition();
  425. }
  426. }
  427. renderIcon = () => {
  428. const { placement } = this.state;
  429. const { showArrow, prefixCls, style } = this.props;
  430. let icon = null;
  431. const triangleCls = classNames([`${prefixCls}-icon-arrow`]);
  432. const bgColor = get(style, 'backgroundColor');
  433. const iconComponent = placement.includes('left') || placement.includes('right') ?
  434. <TriangleArrowVertical /> :
  435. <TriangleArrow />;
  436. if (showArrow) {
  437. if (isValidElement(showArrow)) {
  438. icon = showArrow;
  439. } else {
  440. icon = React.cloneElement(iconComponent, { className: triangleCls, style: { color: bgColor, fill: 'currentColor' } });
  441. }
  442. }
  443. return icon;
  444. };
  445. handlePortalInnerClick = (e: React.MouseEvent) => {
  446. if (this.props.clickToHide) {
  447. this.foundation.hide();
  448. }
  449. if (this.props.stopPropagation) {
  450. stopPropagation(e);
  451. }
  452. };
  453. renderPortal = () => {
  454. const { containerStyle = {}, visible, portalEventSet, placement, transitionState } = this.state;
  455. const { prefixCls, content, showArrow, style, motion, zIndex } = this.props;
  456. const { className: propClassName } = this.props;
  457. const direction = this.context.direction;
  458. const className = classNames(propClassName, {
  459. [`${prefixCls}-wrapper`]: true,
  460. [`${prefixCls}-wrapper-show`]: visible,
  461. [`${prefixCls}-with-arrow`]: Boolean(showArrow),
  462. [`${prefixCls}-rtl`]: direction === 'rtl',
  463. });
  464. const icon = this.renderIcon();
  465. const portalInnerStyle = omit(containerStyle, motion ? ['transformOrigin'] : undefined);
  466. const transformOrigin = get(containerStyle, 'transformOrigin');
  467. const inner = motion ? (
  468. <TooltipTransition position={placement} willEnter={this.willEnter} didLeave={this.didLeave} motion={motion}>
  469. {
  470. transitionState === 'enter' ?
  471. ({ animateCls, animateStyle, animateEvents }) => (
  472. <div
  473. className={classNames(className, animateCls)}
  474. style={{
  475. visibility: 'visible',
  476. ...animateStyle,
  477. transformOrigin,
  478. ...style,
  479. }}
  480. {...portalEventSet}
  481. {...animateEvents}
  482. x-placement={placement}
  483. >
  484. {content}
  485. {icon}
  486. </div>
  487. ) :
  488. null
  489. }
  490. </TooltipTransition>
  491. ) : (
  492. <div className={className} {...portalEventSet} x-placement={placement} style={style}>
  493. {content}
  494. {icon}
  495. </div>
  496. );
  497. return (
  498. <Portal getPopupContainer={this.props.getPopupContainer} style={{ zIndex }}>
  499. <div
  500. className={`${BASE_CLASS_PREFIX}-portal-inner`}
  501. style={portalInnerStyle}
  502. ref={this.setContainerEl}
  503. onClick={this.handlePortalInnerClick}
  504. >
  505. {inner}
  506. </div>
  507. </Portal>
  508. );
  509. };
  510. wrapSpan = (elem: React.ReactNode | React.ReactElement) => {
  511. const { wrapperClassName } = this.props;
  512. const display = get(elem, 'props.style.display');
  513. const block = get(elem, 'props.block');
  514. const style: React.CSSProperties = {
  515. display: 'inline-block',
  516. };
  517. if (block || blockDisplays.includes(display)) {
  518. style.width = '100%';
  519. }
  520. return <span className={wrapperClassName} style={style}>{elem}</span>;
  521. };
  522. mergeEvents = (rawEvents: Record<string, any>, events: Record<string, any>) => {
  523. const mergedEvents = {};
  524. each(events, (handler: any, key) => {
  525. if (typeof handler === 'function') {
  526. mergedEvents[key] = (...args: any[]) => {
  527. handler(...args);
  528. if (rawEvents && typeof rawEvents[key] === 'function') {
  529. rawEvents[key](...args);
  530. }
  531. };
  532. }
  533. });
  534. return mergedEvents;
  535. };
  536. render() {
  537. const { isInsert, triggerEventSet } = this.state;
  538. const { wrapWhenSpecial } = this.props;
  539. let { children } = this.props;
  540. const childrenStyle = { ...get(children, 'props.style') };
  541. const extraStyle: React.CSSProperties = {};
  542. if (wrapWhenSpecial) {
  543. const isSpecial = this.isSpecial(children);
  544. if (isSpecial) {
  545. childrenStyle.pointerEvents = 'none';
  546. if (isSpecial === strings.STATUS_DISABLED) {
  547. extraStyle.cursor = 'not-allowed';
  548. }
  549. children = cloneElement(children as React.ReactElement, { style: childrenStyle });
  550. children = this.wrapSpan(children);
  551. this.isWrapped = true;
  552. } else if (!isValidElement(children)) {
  553. children = this.wrapSpan(children);
  554. this.isWrapped = true;
  555. }
  556. }
  557. // The incoming children is a single valid element, otherwise wrap a layer with span
  558. const newChild = React.cloneElement(children as React.ReactElement, {
  559. ...(children as React.ReactElement).props,
  560. ...this.mergeEvents((children as React.ReactElement).props, triggerEventSet),
  561. style: {
  562. ...get(children, 'props.style'),
  563. ...extraStyle,
  564. },
  565. className: classNames(
  566. get(children, 'props.className')
  567. // `${prefixCls}-trigger`
  568. ),
  569. // to maintain refs with callback
  570. ref: (node: React.ReactNode) => {
  571. // Keep your own reference
  572. (this.triggerEl as any).current = node;
  573. // Call the original ref, if any
  574. const { ref } = children as React.ComponentPropsWithRef<any>;
  575. // this.log('tooltip render() - get ref', ref);
  576. if (typeof ref === 'function') {
  577. ref(node);
  578. } else if (ref && typeof ref === 'object') {
  579. ref.current = node;
  580. }
  581. },
  582. });
  583. // If you do not add a layer of div, in order to bind the events and className in the tooltip, you need to cloneElement children, but this time it may overwrite the children's original ref reference
  584. // So if the user adds ref to the content, you need to use callback ref: https://github.com/facebook/react/issues/8873
  585. return (
  586. <React.Fragment>
  587. {isInsert ? this.renderPortal() : null}
  588. {newChild}
  589. </React.Fragment>
  590. );
  591. }
  592. }
  593. export { Position };