H5 移动端开发小技巧 --- 优雅实现按钮增加点击热区

521 阅读1分钟

如何优雅实现按钮点击热区上下增加 10 px,左右增加 14 px?

function Demo () {
    return (  <button onClick={() => console.log('xxx')}>按钮</button>)
}

方法一:使用伪元素 + absolute 布局

  1. 增加外层包裹元素。
```js
function Demo () {
    return (
+        <div className={styles.btn}>
              <button onClick={() => console.log('xxx')}>按钮</button>
+        </div>
    )
}
  1. 增加样式。
.btn {
    position: relative;
    &::after {
        content: '';
        position: absolute;
        top: -10px;
        right: -14px;
        bottom: -10px;
        left: -14px;
    }
}

问题:代码复用性差。 那么如何增加代码复用性?-- 封装组件

方法二:封装 HotSpot 组件

const HotSpot: React.FC<{
  inset: string
  children: React.ReactElement
}> = ({ children, inset }) => {
  return useMemo(
    () =>
      React.cloneElement(
        children,
        {
          style: { position: 'relative' }
        },
        [
          children?.props?.children,
          <span
            key={`HotSpot_${NP.times(Math.random(), 1000).toFixed(0)}`}
            style={{
              position: 'absolute',
              inset: inset
            }}
          />
        ]
      ),
    []
  )
}

使用方式:

function Demo () {
    return (
        <HotSpot inset="-10px -14px">
            <button onClick={() => console.log('xxx')}>按钮</button>
        </div>
    )
}

完结 🎉