diff --git a/package.json b/package.json index 321123d6c..f618bf695 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "devDependencies": { "@types/classnames": "^2.2.6", "@types/enzyme": "^3.1.15", + "@types/raf": "^3.4.0", "@types/react": "^16.7.17", "@types/react-dom": "^16.0.11", "@types/warning": "^3.0.0", diff --git a/src/SelectTrigger.tsx b/src/SelectTrigger.tsx index b8a71bd87..06f39d895 100644 --- a/src/SelectTrigger.tsx +++ b/src/SelectTrigger.tsx @@ -1,5 +1,6 @@ import classnames from 'classnames'; import * as PropTypes from 'prop-types'; +import raf from 'raf'; import Trigger from 'rc-trigger'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; @@ -98,6 +99,7 @@ export default class SelectTrigger extends React.Component< public saveTriggerRef: (ref: any) => void; public dropdownMenuRef: DropdownMenu | null = null; public triggerRef: any; + public rafInstance: number | null = null; constructor(props: Partial) { super(props); @@ -118,11 +120,24 @@ export default class SelectTrigger extends React.Component< this.setDropdownWidth(); } + public componentWillUnmount() { + this.cancelRafInstance(); + } + public setDropdownWidth = () => { - const dom = ReactDOM.findDOMNode(this) as HTMLDivElement; - const width = dom.offsetWidth; - if (width !== this.state.dropdownWidth) { - this.setState({ dropdownWidth: width }); + this.cancelRafInstance(); + this.rafInstance = raf(() => { + const dom = ReactDOM.findDOMNode(this) as HTMLDivElement; + const width = dom.offsetWidth; + if (width !== this.state.dropdownWidth) { + this.setState({ dropdownWidth: width }); + } + }); + }; + + public cancelRafInstance = () => { + if (this.rafInstance) { + raf.cancel(this.rafInstance); } }; diff --git a/typings/index.d.ts b/typings/index.d.ts index 757ff5815..ae54f7cb4 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -12,6 +12,4 @@ declare module 'rc-util/lib/KeyCode'; declare module 'dom-scroll-into-view'; -declare module 'raf'; - declare module 'rc-trigger';