diff --git a/packages/f2/src/components/tooltip/withTooltip.tsx b/packages/f2/src/components/tooltip/withTooltip.tsx index 46249bc91..caa78ee13 100644 --- a/packages/f2/src/components/tooltip/withTooltip.tsx +++ b/packages/f2/src/components/tooltip/withTooltip.tsx @@ -71,6 +71,14 @@ export interface TooltipProps { custom?: boolean; tooltipMarkerStyle?: any; onChange?: any; + /** + * tooltip 展示回调 + */ + onShow?: () => void; + /** + * tooltip 隐藏回调 + */ + onHide?: () => void; showXTip?: boolean; /** * x 的位置点类型,record 表示按照数据取位置点,coord 表示按照坐标取位置点 @@ -175,11 +183,13 @@ export default (View) => { } showSnapRecords(snapRecords) { - const { chart, onChange } = this.props; + const { chart, onChange, onShow } = this.props; const legendItems = chart.getLegendItems(); const { xField, yField } = snapRecords[0]; const xScale = chart.getScale(xField); const yScale = chart.getScale(yField); + // 如果之前没有records,视为首次出现 + const isInitShow = !this.state.records; const records = snapRecords.map((record) => { const { origin, xField, yField } = record; @@ -214,15 +224,22 @@ export default (View) => { this.setState({ records, }); + if(isInitShow && isFunction(onShow)) { + onShow(); + } if (isFunction(onChange)) { onChange(records); } } hide() { + const { onHide } = this.props; this.setState({ records: null, }); + if(isFunction(onHide)) { + onHide(); + } } render() { diff --git a/packages/f2/test/components/tooltip/tooltip.test.tsx b/packages/f2/test/components/tooltip/tooltip.test.tsx index ffc8c3514..a30d7ace6 100644 --- a/packages/f2/test/components/tooltip/tooltip.test.tsx +++ b/packages/f2/test/components/tooltip/tooltip.test.tsx @@ -1,4 +1,4 @@ -import { Axis, Canvas, Chart, Interval, jsx, Legend, Line, Tooltip } from '../../../src'; +import { Axis, Canvas, Chart, Interval, jsx, Legend, Line, Tooltip, createRef } from '../../../src'; import { createContext, delay, gestureSimulator } from '../../util'; const data = [ @@ -587,4 +587,32 @@ describe('tooltip', () => { await delay(500); expect(context).toMatchImageSnapshot(); }); + + it('Tooltip onShow与onHide钩子触发且每次展示消失仅触发一次', async () => { + const context = createContext('Tooltip onShow与onHide钩子触发且每次展示消失仅触发一次'); + const onShowCb = jest.fn(); + const onHideCb = jest.fn(); + const { props } = ( + + + + + + + + + ); + + const canvas = new Canvas(props); + await canvas.render(); + await delay(1000); + await gestureSimulator(context.canvas, 'touchstart', { x: 30, y: 30 }); + await delay(1000); + await gestureSimulator(context.canvas, 'touchmove', { x: 31, y: 31 }); + await delay(1000); + await gestureSimulator(context.canvas, 'touchend', { x: 32, y: 32 }); + + expect(onShowCb.mock.calls.length).toBe(1); + expect(onHideCb.mock.calls.length).toBe(1); + }); });