React Native View 组件的 onLayout 回调函数
View 的布局发生改变的时候会触发 onLayout 函数,可以在布局发生变化的时候执行一些自定义操作,或者动态调整 UI 元素的样式和布局。
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
layoutWidth: 0,
layoutHeight: 0,
};
}
onLayoutChange = (event) => {
const { width, height } = event.nativeEvent.layout;
this.setState({
layoutWidth: width,
layoutHeight: height,
});
};
render() {
return (
<View onLayout={this.onLayoutChange}>
<Text>My Component</Text>
<Text>Width: {this.state.layoutWidth}</Text>
<Text>Height: {this.state.layoutHeight}</Text>
</View>
);
}
}
export default MyComponent;