简体   繁体   中英

I can't render PreactX component directly into document.body

Please see this minimum example:

编辑cool-meadow-hiv9z

Or Code:

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <title>React App</title>
  </head>

  <body>
    <div id="root"></div>
  </body>
</html>

JS

/** @jsx h */
import { h, render } from "preact";

function App() {
  return <div className="App">Cool</div>;
}

render(<App />, document.body);

The rendered result is this:

Result

<body>
  <div id="root" class="App">Cool</div>
</body>

I want to leave my #root dom element empty, but PreactX take over control to that dom node, why is that happening?

I would like to directly render my PreactX component into document.body.

Preact is basically diffing and merging the original contents of document.body ( <div id="root"></div> ) with the new contents <div className="App">Cool</div> , giving you this result:

<div id="root" class="App">Cool</div>

If you go into public/index.html and remove line 13: <div id="root"></div> , you'll see the generated html is now: <div class="App">Cool</div> .

TLDR; you're mounting preact to document.body , which already has contents, and preact is comparing and merging those contents with your 'App.js' component. Empty the body tag in index.html and you're good.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM