getBoundingClientRect(ref: NodesRef)

版本要求:
@ray-js/ray≥0.5.10

描述

获取节点的坐标信息

参数

参数类型必填说明
是通过 getElementById 获取的节点引用

返回值

类型:Promise<Rect>
包含节点坐标和尺寸信息的 Rect 对象,节点不存在时返回 null

示例代码

基础用法

import React, { useState } from 'react';
import { View, Button, Text, getBoundingClientRect, getElementById } from '@ray-js/ray';

export default function Demo() {
  const [info, setInfo] = useState('');

  const handleGetRect = async () => {
    const element = await getElementById('targetBox');
    if (element) {
      const rect = await getBoundingClientRect(element);
      if (rect) {
        setInfo(`宽:${rect.width} 高:${rect.height} 左:${rect.left} 上:${rect.top}`);
      }
    }
  };

  return (
    <View style={{ padding: 20 }}>
      <View
        id="targetBox"
        style={{
          width: 200,
          height: 100,
          backgroundColor: '#1890ff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Text style={{ color: '#fff' }}>目标区域</Text>
      </View>
      <Button style={{ marginTop: 10 }} onClick={handleGetRect}>
        获取坐标信息
      </Button>
      {info && <Text style={{ marginTop: 10 }}>{info}</Text>}
    </View>
  );
}