Created
September 25, 2018 08:10
-
-
Save 1uokun/e4ed774cb523bbc5425266119de520e5 to your computer and use it in GitHub Desktop.
React.createElement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const React = { | |
createElement: function (tag, attrs, children) { | |
var element = document.createElement(tag); | |
for (let name in attrs) { | |
if (name && attrs.hasOwnProperty(name)) { | |
let value = attrs[name]; | |
if (value === true) { | |
element.setAttribute(name, name); | |
} else if (value !== false && value != null) { | |
element.setAttribute(name, value.toString()); | |
} | |
} | |
} | |
for (let i = 2; i < arguments.length; i++) { | |
let child = arguments[i]; | |
element.appendChild( | |
child.nodeType == null ? | |
document.createTextNode(child.toString()) : child); | |
} | |
return element; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="zh-CN"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>react简单实现-方式2</title> | |
</head> | |
<body> | |
<div id="app"></div> | |
<script src="createElement.js"></script> | |
<script> | |
//args | |
var title = "Hello World"; | |
//event | |
var handleClick = function(){ | |
console.log(123) | |
} | |
document.querySelector('#app').appendChild(React.createElement("div", null, | |
React.createElement("h1", {class:'qwe',onclick:"handleClick()"}, title), | |
React.createElement("h2", null, "This is a template written in TSX, then compiled to JSX by tsc (the Typescript compiler), and finally" + " " + "injected into a web page"))); | |
</script> | |
</body> | |
</html> |
This is a simplified version of how React.createElement()
might conceptually work under the hood. The actual implementation is much more complicated with a ton of other stuff. I don't understand it myself.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi this is really interesting. Is this how createElement actually defined in react package? Can you guide me to the file that defines this. Would be really helpful.