是否有可能获得某个视图的大小(宽度和高度)?例如,我有一个显示进度的视图:

<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} /> 

我需要知道视图的实际宽度以正确对齐其他视图。这可能吗?


当前回答

你可以通过onLayout道具轻松获取视图的大小。

import React from 'react'
import { View } from 'react-native'

export default function index() {
  const onLayout=(event)=> {
    const {x, y, height, width} = event.nativeEvent.layout;
    
  }
  return (
    <View onLayout={onLayout}>
      <OtherComponent />
    </View>
  )
}

每当视图调整大小时,onLayout处理程序也将被调用。

主要的警告是onLayout处理程序是在组件挂载后的一帧首次调用的,因此您可能希望在计算布局之前隐藏UI。

其他回答

对我来说,将尺寸设置为%对我来说是有效的 宽度:100%

你可以通过onLayout道具轻松获取视图的大小。

import React from 'react'
import { View } from 'react-native'

export default function index() {
  const onLayout=(event)=> {
    const {x, y, height, width} = event.nativeEvent.layout;
    
  }
  return (
    <View onLayout={onLayout}>
      <OtherComponent />
    </View>
  )
}

每当视图调整大小时,onLayout处理程序也将被调用。

主要的警告是onLayout处理程序是在组件挂载后的一帧首次调用的,因此您可能希望在计算布局之前隐藏UI。

我创建了这个简单的组件

import React, {Dispatch, SetStateAction} from 'react';
import {View, ViewProps} from 'react-native';

interface GetDimensionsProps {
  children: React.ReactNode | React.ReactNode[];
  onDimensions: Dispatch<SetStateAction<{height: number; width: number}>>;
  viewProps?: ViewProps;
}

export const GetDimensions: React.FC<GetDimensionsProps> = ({
  children,
  onDimensions,
  ...viewProps
}: GetDimensionsProps) => {
  return (
    <View
      onLayout={event =>
        onDimensions({
          width: Math.round(event.nativeEvent.layout.width),
          height: Math.round(event.nativeEvent.layout.height),
        })
      }
      {...viewProps}>
      {children}
    </View>
  );
};

// ────────────────────────────────────────────────────────────────────────────────
// usage

// const [dimensions, setDimensions] = useState<{
//   height: number;
//   width: number;
// }>({width: 0, height: 0});
//
// <GetDimensions onDimensions={setDimensions}>
//  {children}
// </GetDimensions>

下面是获取设备完整视图Dimensions的代码。

var windowSize =维茨。

像这样使用它:

width = windowSize。width, heigth = windowSize。width / 0.565

您可以直接使用Dimensions模块并计算视图的大小。 实际上,Dimensions提供了主要窗口的大小。

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

希望对您有所帮助!

更新:今天使用本地样式表与Flex安排你的视图有助于在广泛的情况下用优雅的布局解决方案编写干净的代码,而不是计算你的视图大小…

尽管构建一个自定义网格组件(它响应主窗口调整大小事件)可以在简单的小部件组件中产生一个很好的解决方案