React Natives Stylesheet.create 是如何工作的?
How does React Natives Stylesheet.create work?
这是创建方法的代码。
create<+S: ____Styles_Internal>(obj: S): $ReadOnly<S> {
// 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) {
if (obj[key]) {
Object.freeze(obj[key]);
}
}
}
return obj;
},
这个函数是如何工作的,<+ 运算符有什么作用?
create<+S: ____Styles_Internal>(obj: S): $ReadOnly<S> {
定义一个名为 create
的函数,它有一个名为 obj
的参数。它是类型注释的,使用Flow,含义如下:
- 参数
obj
是 S
类型,由 obj: S
表示
- 其中
S
是 ____Styles_Internal
的类型或子类型,由 <+S: ____Styles_Internal>
表示。 +
是一个 variance sigil signifying covariant 类型被接受(类型是子类型,连同类型本身)
- return 类型是
obj
的只读版本,由 $ReadOnly<S>
表示
if (__DEV__) {
for (const key in obj) {
if (obj[key]) {
Object.freeze(obj[key]);
}
}
}
for...in
iterates over enumerable properties and if the value of the property is truthy, the value is frozen by Object.freeze
. The value would normally be an object (see examples 来自 React Native 关于样式表的文档)所以冻结它会阻止对象被更改。这些事情只有在 __DEV__
变量是true
,表示代码在开发环境中是运行。
我没有编写代码,所以我只能推测为什么它会这样:
- 根据代码作者的 commit 消息:
,此行为可能只发生在开发中,因为它可能会破坏生产应用程序
I don't really know if we have/need any safer way of rolling this out than just landing it. It can break if the object passed to StyleSheet.create is mutated afterwards but that isn't a practice anywhere I've seen.
- 不知道为什么冻结与否的测试是真实的
- 我不确定为什么对象需要冻结,但我怀疑这是为了消除变异样式对象的意外副作用,因为 React 可能会通过引用比较渲染之间的样式对象。
return obj;
},
Returns 对象。
进一步阅读
这是创建方法的代码。
create<+S: ____Styles_Internal>(obj: S): $ReadOnly<S> {
// 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) {
if (obj[key]) {
Object.freeze(obj[key]);
}
}
}
return obj;
},
这个函数是如何工作的,<+ 运算符有什么作用?
create<+S: ____Styles_Internal>(obj: S): $ReadOnly<S> {
定义一个名为 create
的函数,它有一个名为 obj
的参数。它是类型注释的,使用Flow,含义如下:
- 参数
obj
是S
类型,由obj: S
表示
- 其中
S
是____Styles_Internal
的类型或子类型,由<+S: ____Styles_Internal>
表示。+
是一个 variance sigil signifying covariant 类型被接受(类型是子类型,连同类型本身) - return 类型是
obj
的只读版本,由$ReadOnly<S>
表示
if (__DEV__) {
for (const key in obj) {
if (obj[key]) {
Object.freeze(obj[key]);
}
}
}
for...in
iterates over enumerable properties and if the value of the property is truthy, the value is frozen by Object.freeze
. The value would normally be an object (see examples 来自 React Native 关于样式表的文档)所以冻结它会阻止对象被更改。这些事情只有在 __DEV__
变量是true
,表示代码在开发环境中是运行。
我没有编写代码,所以我只能推测为什么它会这样:
- 根据代码作者的 commit 消息: ,此行为可能只发生在开发中,因为它可能会破坏生产应用程序
I don't really know if we have/need any safer way of rolling this out than just landing it. It can break if the object passed to StyleSheet.create is mutated afterwards but that isn't a practice anywhere I've seen.
- 不知道为什么冻结与否的测试是真实的
- 我不确定为什么对象需要冻结,但我怀疑这是为了消除变异样式对象的意外副作用,因为 React 可能会通过引用比较渲染之间的样式对象。
return obj;
},
Returns 对象。