如何通过重用另一个对象的代码来制作 React Native Flexbox StyleSheet 对象
How to make a React Native Flexbox StyleSheet object by reusing code from another object
在我的 React Native 项目中创建一个 StyleSheet 对象时,我经常想创建一个与另一个非常相似的属性对象,只需进行一两个更改。 过去,我只是复制对象并更改名称和一两个属性,但我一直认为必须有一个不涉及复制/粘贴的更好解决方案。 我想过扩展一个对象,但不确定如何在创建样式表的上下文中做到这一点。 我不知道我是否使用了正确的术语,所以我只用下面的代码来说明。
var styles = StyleSheet.create({
titleText: {
marginLeft: 8,
marginTop: 0,
marginBottom: 0,
alignSelf: "left",
color: "grey",
fontSize: 15,
},
buttonText: {
marginLeft: 8,
marginTop: 0,
marginBottom: 0,
alignSelf: "left",
color: "grey",
fontSize: 20,
},
});
在这个例子中,我想从titleText复制buttonText,但只需在将属性传递给StyleSheet.create()语句的上下文中更改fontSize值。 有没有比像上面一样写出来更好的方法? 我觉得必须有,因为众所周知,程序员讨厌重复代码。
我尝试使用不可变性助手做一些类似buttonText: update(titleText, {$merge: {fontSize: 20}})
的事情,但这给出了"未定义更新"错误。
要记住的一件事是,传递的最后一个属性将是使用的属性。因此,您可以设置如下内容:
var styles = StyleSheet.create({
titleText: {
marginLeft: 8,
marginTop: 0,
marginBottom: 0,
alignSelf: "left",
color: "grey",
fontSize: 15,
},
buttonText: {
fontSize: 20,
},
});
并像这样使用它:
<Text style={ [styles.titleText, styles.buttonText] } >....</Text>
这将继承 titleText 的所有样式,仅应用较大的字体大小。
Javascript有一个名为assign
的对象继承方法,它是Object类的一部分。因此,由于StyleSheet.create
只接收常规对象,因此您可以使用它。
let buttonDefaults = {
marginLeft: 8,
marginTop: 0,
marginBottom: 0,
alignSelf: "left",
color: "grey",
fontSize: 15,
}
let styles = StyleSheet.create({
//titleText simply makes a copy, doesn't change it
titleText: Object.assign(buttonDefaults, {}),
//you could also do this and it would work, just not copy the object:
//titleText: buttonDefaults,
//buttonText copies the values, and can add new ones or overwrite
buttonText: Object.assign(buttonDefaults, {
paddingLeft: 5, //new value
fontSize: 20, //overwrite value
}),
});
通过这种方式,您甚至可以在其他地方为整个应用程序制作默认样式表
相关文章:
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- 使用Jest测试React Native应用程序
- 是否存在React Native“;WEB代码安全防护”;
- React Native Listview留有余地
- 如何在React Native中绘制图形
- 在iOS和Android上使用React native时,我还能使用本机第三方lirbraries吗
- 使用createContainer将Meteor数据获取到React Native中时出现问题
- React Native当前是否支持访问用户'的通讯簿
- React Native-What'It’在任何地方都要留下逗号
- React Native DeviceEventEmitter键盘WillShow停止工作
- 与React Native的Chart.js等效
- 如何使用webview在React Native中使用Highcharts
- 如何在React Native的MapView中设置标记
- React Native NavigatorIOS
- 如何获得React Native TextInput以在提交后保持焦点
- 使用react native检测应用程序终止
- 可以在React Native中制作一个自哈希应用程序
- React Native AlertOS api中可能有多个文本字段
- react native中常见的js模块
- 在React Native+Redux中使用Navigator