React Native中绝对定位图片无法居中的异常问题
问题原因
- StyleSheet静态特性限制:
StyleSheet.create在组件初始化阶段就已执行,此时logo_X和logo_Y的初始值为0,后续修改全局变量不会触发StyleSheet重新生成样式,图片始终使用初始的0值定位。 - 全局变量不触发组件重渲染:修改全局变量不会驱动组件的
render方法重新执行,即便变量值计算正确,视图也不会更新。
解决方法
方法一:用组件State管理坐标(适配原有逻辑)
将计算后的坐标存入组件state,动态为Image设置样式,state更新时会触发重渲染,应用最新的定位值。
修改后代码示例:
import React, { Component } from "react"; import { Dimensions, Image, SafeAreaView, ScrollView, StyleSheet, View } from "react-native"; const halfWidth = Dimensions.get("window").width / 2; const halfHeight = Dimensions.get("window").height / 2; const logoImage = require('./images/logo_white_128.png'); export default class Initial extends Component { constructor(props) { super(props); this.state = { logoX: 0, logoY: 0 }; } getDims = () => { const source = Image.resolveAssetSource(logoImage); const logoWidth = source.width; const logoHeight = source.height; const logoX = halfWidth - (logoWidth / 2); const logoY = halfHeight - (logoHeight / 2); this.setState({ logoX, logoY }); } componentDidMount() { this.getDims(); } render() { return ( <> <SafeAreaView style={styles.container}> <ScrollView style={styles.scrollView}> <Image style={[styles.img, { top: this.state.logoY, left: this.state.logoX }]} source={logoImage} /> </ScrollView> </SafeAreaView> </> ) } } const styles = StyleSheet.create({ container: { flex: 1 }, scrollView: { flex: 1 }, img: { position: "absolute" } });
方法二:无需获取图片尺寸,直接用绝对定位居中技巧(更简洁)
利用绝对定位布局特性,设置left:0, right:0, top:0, bottom:0并配合margin: 'auto',让图片自动居中,无需手动计算坐标,代码更简洁可靠。
代码示例:
import React, { Component } from "react"; import { SafeAreaView, ScrollView, StyleSheet, Image, View } from "react-native"; export default class Initial extends Component { render() { return ( <> <SafeAreaView style={styles.container}> <ScrollView style={styles.scrollView}> <Image style={styles.img} source={require('./images/logo_white_128.png')} /> </ScrollView> </SafeAreaView> </> ) } } const styles = StyleSheet.create({ container: { flex: 1 }, scrollView: { flex: 1 }, img: { position: "absolute", left: 0, right: 0, top: 0, bottom: 0, margin: "auto" } });
注:若ScrollView内容会滚动,绝对定位的图片会相对于ScrollView视口定位;若要让图片相对于整个屏幕居中,需将图片放在ScrollView外部,或确保ScrollView设置flex:1并占满屏幕。
内容的提问来源于stack exchange,提问作者Pangit
相关产品推荐
相关产品推荐

