我正在尝试使用 preact 学习 dom 的补液。由于某种未知的原因,该render
函数并没有替换原始的 DOM 节点,而是附加到它上面。
https://github.com/preactjs/preact/issues/24,第三个参数render
应该有机会替换:
render(<App />, into, into.lastChild);
https://codesandbox.io/s/beautiful-leavitt-rkwlw?file=/index.html:0-1842
问题:关于如何确保水合作用如人们所期望的那样工作的任何想法,例如用交互式计数器替换静态计数器?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
</head>
<body>
<script>
window.__STATE__ = { components: {} };
</script>
<main>
<div>
<script data-cmp-id="1">
window.__STATE__.components[1] = {
name: "Counter",
props: { id: 1 }
};
</script>
<div>HOW MANY LIKES 0</div>
<button>Increment</button>
</div>
</main>
<script type="module">
import {
html,
useState,
render
} from "https://unpkg.com/htm/preact/standalone.module.js";
let id = 0;
export const withHydration = Component => props => {
id += 1;
return html`
<${Component} ...${props} />
`;
};
const Counter = () => {
const [likes, setLikes] = useState(0);
const handleClick = e => {
e.preventDefault();
setLikes(likes + 1);
};
return html`
<div>HOW MANY LIKES ${likes}</div>
<button onClick=${handleClick}>Increment</button>
`;
};
const componentMap = {
Counter: withHydration(Counter)
};
const $componentMarkers = document.querySelectorAll(`[data-cmp-id]`);
Array.from($componentMarkers).forEach($marker => {
debugger;
const $component = $marker.nextElementSibling;
const { name, props } = window.__STATE__.components[
$marker.dataset.cmpId
];
const Component = componentMap[name];
render(
html`
<${Component} ...${props} />
`,
$component.parentNode,
$component
);
});
</script>
</body>
</html>
所有这些都受到https://github.com/maoberlehner/eleventy-preact repo 的启发。