Skip to content

Instantly share code, notes, and snippets.

@1uokun
Created September 25, 2018 08:10
Show Gist options
  • Save 1uokun/e4ed774cb523bbc5425266119de520e5 to your computer and use it in GitHub Desktop.
Save 1uokun/e4ed774cb523bbc5425266119de520e5 to your computer and use it in GitHub Desktop.
React.createElement
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;
}
};
<!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>
@TejushAegis
Copy link

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.

@rudy-banerjee
Copy link

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.

https://github.com/facebook/react/blob/a4195750779dbd9a13e1615fbbd493bf2c5768ca/packages/react/src/ReactElement.js#L362

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment