gpt4 book ai didi

react-native - React Native 中 StyleSheet.create 的用途

转载 作者:行者123 更新时间:2023-12-03 13:35:31 27 4
gpt4 key购买 nike

我想问社区关于 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 中创建全局样式,并将其添加到需要对对象进行样式设置的相应 View 中。

一些像 TextInput、Text、Button 这样的小部件无法应用 React Native 中的几乎所有 css 样式。

因此,在这些情况下,您可以做的是包装这些小部件,然后可以使用 StyleSheet.create() 方法创建全局样式表以全局使用并减少您的头痛。

因此,您的问题的结论可以总结为 Stylesheet.create() 有助于提高性能,同时使用相同样式设置多个 View 的样式每次都会为每个 View 创建一个新对象。

而 Stylesheet.create() 将充当所有 View 的单个全局对象,这些 View 使用它来设置自己的样式,从而导致性能/内存优化。

关于react-native - React Native 中 StyleSheet.create 的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212364/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com