Created
November 5, 2019 07:56
-
-
Save bramblex/58835db69abc92c4dce09c2374bfb8c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { PureComponent, createRef } from 'react'; | |
/** | |
* @class ExtendClickArea | |
* @argument {PureComponent<{ extend: number, center: boolean }>} | |
* @description 用来自动扩展按钮的点击区域 | |
**/ | |
export default class ExtendClickArea extends PureComponent { | |
/** @type {{ width: number, height: number }} */ | |
state = { width: 0, height: 0 }; | |
elRef = createRef(); | |
reCalculate() { | |
/** @type {(HTMLElement | null)} */ | |
const el = this.elRef.current; | |
if (!el) { | |
return; | |
} | |
/** @type {(HTMLElement | null)} */ | |
const parent = el.parentElement; | |
if (!el) { | |
return; | |
} | |
this.setState({ | |
width: parent.offsetWidth, | |
height: parent.offsetHeight, | |
}); | |
} | |
componentDidMount() { | |
this.reCalculate(); | |
} | |
render() { | |
const { extend, center } = this.props; | |
const { width, height } = this.state; | |
const style = { | |
position: 'absolute', | |
marginLeft: center ? -extend : 0, | |
marginTop: center ? -extend : 0, | |
width: width + 2 * extend, | |
height: height + 2 * extend, | |
}; | |
return <div ref={this.elRef} style={style}></div>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment