https://github.com/facebook/react/blob/master/packages/react-dom/src/client/ReactDOMLegacy.js
将参数 一层层 传递,最终是对根原元素的更新。
render
--return–> legacyRenderSubtreeIntoContainer
--return–>getPublicRootInstance
export function render(
element: React$Element<any>, // 要渲染的元素( string / classComponent / FunctionComponent )
container: Container, // 根节点 root React.Fragment
callback: ?Function, // 渲染完成执行的回调
) {
invariant(
isValidContainer(container), // 判断 更节点是否有效,并返回相应的提示。
'Target container is not a DOM element.',
);
return legacyRenderSubtreeIntoContainer(
null,
element,
container,
false,
callback,
);
}
}
function legacyRenderSubtreeIntoContainer(
parentComponent: ?React$Component<any, any>, // null
children: ReactNodeList, // 要渲染的元素
container: Container, // 根节点
forceHydrate: boolean, // false
callback: ?Function, // 渲染完成执行的回调
) {
// root => _reactRootContainer => _internalRoot 知道存在该属性
let root: RootType = (container._reactRootContainer: any); // 接收根节点
let fiberRoot;
if (!root) {... // 根元素不存在的处理,不过一般都会有根元素。}
else {
fiberRoot = root._internalRoot;
if (typeof callback === 'function') {
const originalCallback = callback;
callback = function() {
const instance = getPublicRootInstance(fiberRoot);
originalCallback.call(instance);
};
}
// Update
updateContainer(children, fiberRoot, parentComponent, callback); // 暂时不要去关注
}
return getPublicRootInstance(fiberRoot);
}
export function getPublicRootInstance(
container: OpaqueRoot, // 根元素相关对象
): React$Component<any, any> | PublicInstance | null {
const containerFiber = container.current;
if (!containerFiber.child) {
return null;
}
switch (containerFiber.child.tag) {
case HostComponent: // export const HostComponent = 5;
return getPublicInstance(containerFiber.child.stateNode); // 传入啥返回啥
// export function getPublicInstance(instance) {
// return instance;
// }
default:
return containerFiber.child.stateNode; // 当前根元素(FiberRootNode)
}
}
细节说明
// other
function Container({children, updates}) {
const [step, setStep] = useState(0);
useLayoutEffect(() => {if (updates !== undefined) {...}}, [updates]);
// children 为 根元素的 children => HTMLCollection
return <React.Fragment key={step}>{children}</React.Fragment>;
}