【发布时间】:2019-12-06 11:34:35
【问题描述】:
我想向社区询问有关 React Native 中 StyleSheet.create 的变化。
之前:
我已经回顾了过去有关此主题的问题,例如this question,但它们都在很久以前得到了回答(除了this answer,但我想有一些明确的东西)并且很多都发生了变化自从。
在 StyleSheet 为样式创建唯一 ID 之前,主要用于性能优化。如果您想从创建的样式对象中获取样式,您应该使用flatten 方法。大多数答案都引用了这种 flatten 方法,并且您无法像访问普通对象一样访问样式属性。
例如
const styles = StyleSheet.create({
modalContainer: {
width: 100,
backgroundColor: 'white',
padding: 5,
},
你可以不访问像styles.modalContainer.padding;这样的填充样式
目前:
但是,它的行为已经改变。 This is the source code of StyleSheet 来自 React Native 团队。只是复制create方法:
create<+S: ____Styles_Internal>(obj: S): $ObjMap<S, (Object) => any> {
// TODO: This should return S as the return type. But first,
// we need to codemod all the callsites that are typing this
// return value as a number (even though it was opaque).
if (__DEV__) {
for (const key in obj) {
StyleSheetValidation.validateStyle(key, obj);
if (obj[key]) {
Object.freeze(obj[key]);
}
}
}
return obj;
},
};
这只是返回传递给 create 的对象,而不对其进行任何操作。所以您可以以styles.modalContainer.padding;
也许我对 TODO 的理解不是很清楚,但是这种方法至少从 RN 0.57 开始就是这样编码的,我不知道他们是否会改回来。
我的问题:
再使用StyleSheet.create还有意义吗?
提前感谢您分享您的意见!
【问题讨论】:
-
为了验证和代码拆分,我认为值得使用!
标签: react-native