是否有可能获得某个视图的大小(宽度和高度)?例如,我有一个显示进度的视图:
<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} />
我需要知道视图的实际宽度以正确对齐其他视图。这可能吗?
是否有可能获得某个视图的大小(宽度和高度)?例如,我有一个显示进度的视图:
<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} />
我需要知道视图的实际宽度以正确对齐其他视图。这可能吗?
当前回答
您可以直接使用Dimensions模块并计算视图的大小。 实际上,Dimensions提供了主要窗口的大小。
import { Dimensions } from 'Dimensions';
Dimensions.get('window').height;
Dimensions.get('window').width;
希望对您有所帮助!
更新:今天使用本地样式表与Flex安排你的视图有助于在广泛的情况下用优雅的布局解决方案编写干净的代码,而不是计算你的视图大小…
尽管构建一个自定义网格组件(它响应主窗口调整大小事件)可以在简单的小部件组件中产生一个很好的解决方案
其他回答
下面是获取设备完整视图Dimensions的代码。
var windowSize =维茨。
像这样使用它:
width = windowSize。width, heigth = windowSize。width / 0.565
这是唯一对我有效的方法:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class Comp extends Component {
find_dimesions(layout){
const {x, y, width, height} = layout;
console.warn(x);
console.warn(y);
console.warn(width);
console.warn(height);
}
render() {
return (
<View onLayout={(event) => { this.find_dimesions(event.nativeEvent.layout) }} style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('Comp', () => Comp);
对我来说,将尺寸设置为%对我来说是有效的 宽度:100%
您可以直接使用Dimensions模块并计算视图的大小。 实际上,Dimensions提供了主要窗口的大小。
import { Dimensions } from 'Dimensions';
Dimensions.get('window').height;
Dimensions.get('window').width;
希望对您有所帮助!
更新:今天使用本地样式表与Flex安排你的视图有助于在广泛的情况下用优雅的布局解决方案编写干净的代码,而不是计算你的视图大小…
尽管构建一个自定义网格组件(它响应主窗口调整大小事件)可以在简单的小部件组件中产生一个很好的解决方案
我创建了这个简单的组件
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>