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