Last active
September 25, 2018 08:15
-
-
Save 1uokun/bcfaec28d8c5051be343ca390bb3001e to your computer and use it in GitHub Desktop.
React simple Component
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
/** | |
* @param type | string | element | |
* @param node.props | object | attr/event | |
* @param node.children | array | loop top/textNode | |
* */ | |
class Component { | |
constructor(){ | |
document.getElementById('app').appendChild(this.createElement(this.render())) | |
} | |
createElement(node){ | |
if(typeof node === 'string') { | |
return document.createTextNode(node) | |
} | |
const $el = document.createElement(node.type) | |
if(node.props&&JSON.stringify(node.props) !== '{}'){ | |
for(let propName in node.props){ | |
let propValue = node.props[propName]; | |
//props events | |
if(typeof propValue === 'function'){ | |
$el.addEventListener( | |
propName, | |
propValue | |
); | |
}else { | |
//props attr | |
$el.setAttribute(propName, propValue) | |
} | |
} | |
} | |
node.children.map(a=>{ | |
$el.appendChild(this.createElement(a)) | |
}); | |
return $el | |
} | |
} |
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 component简单实现</title> | |
</head> | |
<body> | |
<div id="app"></div> | |
<script src="Component.js"></script> | |
<script> | |
class View extends Component{ | |
change(e){ | |
console.log(e.target.value) | |
} | |
render(){ | |
return {type:'ul', props:{}, children:[ | |
{type:'li',props:{class:'list'},children:[ | |
{type:'input', props:{value:'Niko',class:'list',keyup:this.change},children:[]}, | |
]}, | |
{type:'li', props:{},children:['Bellic']} | |
]} | |
} | |
} | |
new View() | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment