mirror of
https://github.com/codecrafters-io/build-your-own-x
synced 2026-07-03 01:09:25 +00:00
virtual dom
This commit is contained in:
parent
7d328895c4
commit
32189f86a2
3 changed files with 62 additions and 0 deletions
57
virtual_dom_with_JS/dom.jsx
Normal file
57
virtual_dom_with_JS/dom.jsx
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
/**@jsx h */
|
||||||
|
function h(type, props, ...children) {
|
||||||
|
return { type, props: props || {}, children };
|
||||||
|
}
|
||||||
|
function setBoolean($target, name, value) {
|
||||||
|
if (value) {
|
||||||
|
$target.setAttribute(name, value);
|
||||||
|
$target[name] = true;
|
||||||
|
} else {
|
||||||
|
$target[name] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCustomProp(name) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
function setProp($target, name, value) {
|
||||||
|
if (isCustomProp(name)) {
|
||||||
|
return;
|
||||||
|
} else if (name === "className") {
|
||||||
|
$target.setAttribute("class", value);
|
||||||
|
} else if (typeof value === "boolean") {
|
||||||
|
setBoolean($target, name, value);
|
||||||
|
} else {
|
||||||
|
$target.setAttribute(name, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setProps($target, props) {
|
||||||
|
Object.keys(props).forEach((name) => {
|
||||||
|
setProp($target, name, props[name]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createElement(node) {
|
||||||
|
if (typeof node === "string") {
|
||||||
|
return document.createTextNode(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
const $el = document.createElement(node.type);
|
||||||
|
setProps($el, node.props);
|
||||||
|
node.children.map(createElement).forEach($el.appendChild.bind($el));
|
||||||
|
return $el;
|
||||||
|
}
|
||||||
|
|
||||||
|
const f = (
|
||||||
|
<ul style="list-style:none;">
|
||||||
|
<li className="item">item 1</li>
|
||||||
|
<li className="item">
|
||||||
|
<input type="checkbox" checked={true} />
|
||||||
|
<input type="text" checked={true} />
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
|
||||||
|
const $root = document.getElementById("root");
|
||||||
|
$root.appendChild(createElement(f));
|
||||||
1
virtual_dom_with_JS/inde.html
Normal file
1
virtual_dom_with_JS/inde.html
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<div id="root"></div>
|
||||||
4
virtual_dom_with_JS/index.css
Normal file
4
virtual_dom_with_JS/index.css
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
.item {
|
||||||
|
background: yellow;
|
||||||
|
margin: 10px 0;
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue