Skip to content

Instantly share code, notes, and snippets.

@1uokun
Last active September 25, 2018 08:15
Show Gist options
  • Save 1uokun/bcfaec28d8c5051be343ca390bb3001e to your computer and use it in GitHub Desktop.
Save 1uokun/bcfaec28d8c5051be343ca390bb3001e to your computer and use it in GitHub Desktop.
React simple Component
/**
* @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
}
}
<!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