跳到主要内容

React DOM 片段引用共享

// 比较空片段的文档位置
export function compareDocumentPositionForEmptyFragment<TPublicInstance>(
fragmentFiber: Fiber,
parentHostInstance: TPublicInstance,
otherNode: TPublicInstance,
getPublicInstance: (fiber: Fiber) => TPublicInstance,
): number {
let result;
// If the fragment has no children, we can use the parent and
// siblings to determine a position.
// 如果片段没有子元素,我们可以使用父元素和兄弟元素来确定位置。
const parentResult = parentHostInstance.compareDocumentPosition(otherNode);
result = parentResult;
if (parentHostInstance === otherNode) {
result = Node.DOCUMENT_POSITION_CONTAINS;
} else {
if (parentResult & Node.DOCUMENT_POSITION_CONTAINED_BY) {
// otherNode is one of the fragment's siblings. Use the next
// sibling to determine if its preceding or following.
// otherNode 是片段的其中一个兄弟节点。使用下一个兄弟节点来判断它是前一个还是后一个。
const nextSiblingFiber = getNextSiblingHostFiber(fragmentFiber);
if (nextSiblingFiber === null) {
result = Node.DOCUMENT_POSITION_PRECEDING;
} else {
const nextSiblingInstance = getPublicInstance(nextSiblingFiber);
const nextSiblingResult =
nextSiblingInstance.compareDocumentPosition(otherNode);
if (
nextSiblingResult === 0 ||
nextSiblingResult & Node.DOCUMENT_POSITION_FOLLOWING
) {
result = Node.DOCUMENT_POSITION_FOLLOWING;
} else {
result = Node.DOCUMENT_POSITION_PRECEDING;
}
}
}
}

result |= Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
return result;
}