是否有可能获得某个视图的大小(宽度和高度)?例如,我有一个显示进度的视图:
<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} />
我需要知道视图的实际宽度以正确对齐其他视图。这可能吗?
是否有可能获得某个视图的大小(宽度和高度)?例如,我有一个显示进度的视图:
<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} />
我需要知道视图的实际宽度以正确对齐其他视图。这可能吗?
当前回答
也许你可以用measure:
measureProgressBar() {
this.refs.welcome.measure(this.logProgressBarLayout);
},
logProgressBarLayout(ox, oy, width, height, px, py) {
console.log("ox: " + ox);
console.log("oy: " + oy);
console.log("width: " + width);
console.log("height: " + height);
console.log("px: " + px);
console.log("py: " + py);
}
其他回答
我创建了这个简单的组件
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>
从React Native 0.4.2开始,视图组件就有了onLayout道具。传入一个接受事件对象的函数。事件的nativeEvent包含了视图的布局。
<View onLayout={(event) => {
var {x, y, width, height} = event.nativeEvent.layout;
}} />
每当视图调整大小时,onLayout处理程序也将被调用。
主要的警告是onLayout处理程序是在组件挂载后的一帧首次调用的,因此您可能希望在计算布局之前隐藏UI。
对我来说,将尺寸设置为%对我来说是有效的 宽度:100%
下面是获取设备完整视图Dimensions的代码。
var windowSize =维茨。
像这样使用它:
width = windowSize。width, heigth = windowSize。width / 0.565
也许你可以用measure:
measureProgressBar() {
this.refs.welcome.measure(this.logProgressBarLayout);
},
logProgressBarLayout(ox, oy, width, height, px, py) {
console.log("ox: " + ox);
console.log("oy: " + oy);
console.log("width: " + width);
console.log("height: " + height);
console.log("px: " + px);
console.log("py: " + py);
}