如何为React样式对象添加参数?动态修改高度的语法问题
修复带参数的共享样式语法错误并实现动态高度修改
问题描述
我有一段存在语法错误的React Native共享样式代码,希望修改成可接收参数的形式,以便调用时动态修改高度。错误代码如下:
export const modalStyle(height)= { // <-- 此处添加参数的正确语法是什么? width:MODAL_WIDTH, height:height, backgroundColor:color_theme_light.mainGreen, borderRadius:22, justifyContent:"center", alignItems:"center", shadowColor: "#000", shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.20, shadowRadius: 1.41, elevation: 2 }
预期的调用方式如下:
import {modalStyle} from './modalStyles' <View style={modalStyle(40)}> ... </View>
解决方法
核心是把modalStyle从常量对象改成返回样式对象的函数,这样就能接收参数并动态生成样式。
正确的样式代码
export const modalStyle = (height) => { return { width: MODAL_WIDTH, height: height, backgroundColor: color_theme_light.mainGreen, borderRadius: 22, justifyContent: "center", alignItems: "center", shadowColor: "#000", shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.20, shadowRadius: 1.41, elevation: 2 }; };
简化写法(可选)
如果函数仅返回样式对象,可以省略return和外层大括号,用箭头函数的简洁写法:
export const modalStyle = (height) => ({ width: MODAL_WIDTH, height: height, backgroundColor: color_theme_light.mainGreen, borderRadius: 22, justifyContent: "center", alignItems: "center", shadowColor: "#000", shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.20, shadowRadius: 1.41, elevation: 2 });
调用验证
修改完成后,即可按照预期方式调用:
import {modalStyle} from './modalStyles' <View style={modalStyle(40)}> ... </View>
内容的提问来源于stack exchange,提问作者AnyamBorogass
相关产品推荐
相关产品推荐

