So I know this question has already been asked but I couldn't find what I was looking for. I've been trying to better understand how react works.
import React from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";
function App() {
return (
<Button variant="contained" color="primary">
Hello World
</Button>
);
}
ReactDOM.render(<App />, document.querySelector("#app"));
In the example above the render function takes the App component as the first parameter. I think I'm right in saying this is a JSX React element. But how does the render function then call the App function so that is returns its JSX code? And how does it work when its a class component instead of a functional component? I tried looking through React's source code but had trouble finding anything.
ReactDOM.render(<App />, document.querySelector("#app"));
is roughly equal to this
document.querySelector("#app").innerHTML = babel-compiled version of App
basically that app component will be handed to babel to be transpiled from jsx to native js, and the it would be put inside that root
; doesn't matter what kind of thing is that, is it class
based or function
based, babel will handle that
If you check the index.html, you will have this:
<div id="root"></div>
consider this element this as the parent element. this is what render() does behind the scene. first lets choose the parent element.
const parentElement=document.getElementById("root")
now we need to append some html to it.
const templateElement = document.createElement("template");
we create a template element. template element is an actual HTML element that turns some string into some actua html that can be stuck into the DOM. now we jsut created this
<template></template>
we need to pass some html elements in it. in your eaxample it is App
component.
templateElement.innerHTML = </App>
now we need to append this to the parent element:
parentElement.append(templateElement.content);
so you can think render function like this.
//instead of Component, you can jsut pass any html code directly. it will eventually be attached to the template element
render(Component,parentElement) {
const templateElement = document.createElement("template");
templateElement.innerHTML = Component;
parentElement.append(templateElement.content);
}
in the first line, I create the template element. then I pass a template
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.