React Native中如何使用left与right属性拉伸View组件
React Native 实现left/right拉伸绝对定位View的方案
React Native 本身支持通过同时给绝对定位元素设置left和right属性自动拉伸宽度,和Web端CSS逻辑一致,你原代码未生效的常见原因和解决方法如下:
修正后可运行代码
import { View, Text, StyleSheet } from 'react-native'; export default function App() { return ( <View style={styles.container}> <View style={{ position: 'absolute', left: 100, right: 20, top: 200, // 可自行调整垂直位置,不配置时默认渲染在父容器顶部 height: 50, backgroundColor: 'orange' }}> <Text>hello there</Text> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
兼容低版本的替代方案
如果你使用的是0.59及以下的旧版本React Native,不支持left+right自动计算宽度,可以用屏幕宽度手动计算:
import { View, Text, StyleSheet, Dimensions } from 'react-native'; // 获取屏幕宽度 const screenWidth = Dimensions.get('window').width; export default function App() { return ( <View style={styles.container}> <View style={{ position: 'absolute', left: 100, width: screenWidth - 100 - 20, // 手动计算宽度:总宽度减去left和right的数值 top: 200, height: 50, backgroundColor: 'orange' }}> <Text>hello there</Text> </View> </View> ); } // 其余样式保持不变
内容的提问来源于stack exchange,提问作者user15573857
相关产品推荐
相关产品推荐

