类型标记

export declare const enum ShapeFlags {
    ELEMENT = 1, // 1
    FUNCTIONAL_COMPONENT = 2, // 10
    STATEFUL_COMPONENT = 4, // 100
    TEXT_CHILDREN = 8, // 1000
    ARRAY_CHILDREN = 16, // 10000
    SLOTS_CHILDREN = 32, // 100000
    TELEPORT = 64, // 1000000
    SUSPENSE = 128, // 10000000
    COMPONENT_SHOULD_KEEP_ALIVE = 256, // 100000000
    COMPONENT_KEPT_ALIVE = 512, // 1000000000
    COMPONENT = 6 // 110
}

按位与:

01 | 01 === 01
01 | 10 === 11
10 | 10 === 10

判断类型的按位且:

11 & 11 === 11
01 & 10 === 00
10 & 10 === 10

对应位置1 & 1 === 1, 1 | 0 === 0,就像&&的逻辑,要满足所有为真值。

比如100代表STATEFUL_COMPONENT类型,10000代表ARRAY_CHILDREN类型,合并使用

const initial = 100 | 10000 === 10100

要判断10100是否包含STATEFUL_COMPONENT类型:

const result = initial & ShapeFlags.STATEFUL_COMPONENT
// result ===  100
if (result > 0) {
    console.log('包含STATEFUL_COMPONENT类型')
}

利用标记的方式,可以轻松合并类型和检测类型,对代码的可阅读性强。

results matching ""

    No results matching ""