Skip to content

Instantly share code, notes, and snippets.

@bramblex
Created November 5, 2019 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bramblex/58835db69abc92c4dce09c2374bfb8c4 to your computer and use it in GitHub Desktop.
Save bramblex/58835db69abc92c4dce09c2374bfb8c4 to your computer and use it in GitHub Desktop.
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