React Native开发中如何向样式表传递prop实现动态条件样式?
问题原因
StyleSheet.create 是组件外部定义的静态配置,执行时机早于组件渲染,无法访问组件内部接收的 isProfile prop,所以你的条件判断逻辑不会生效。
正确实现方案
推荐把静态样式保留在 StyleSheet 中,动态高度通过内联样式拼接传入,性能最优:
import { StyleSheet, View } from 'react-native'; function Feed({isProfile}){ return( {/* style属性支持传入数组,后定义的样式会覆盖前面对象的同名属性 */} <View style={[ styles.container, { height: isProfile ? windowHeight : windowHeight * 0.87 } ]}> </View> ) } const styles = StyleSheet.create({ container:{ backgroundColor: colors.primary, width: windowWidth, justifyContent: "center", // 移除这里的动态height配置 } })
如果你的动态样式属性较多,也可以直接在组件内部封装动态样式对象:
function Feed({isProfile}){ const dynamicStyles = { height: isProfile ? windowHeight : windowHeight * 0.87 // 可以继续加其他动态样式属性 } return( <View style={[styles.container, dynamicStyles]}> </View> ) }
内容的提问来源于stack exchange,提问作者user17264015
相关产品推荐
相关产品推荐

