React Hello World Example with ES6+JSX
A basic Hello World widget with in browser JSX transformed + ES6 support
by yan kang
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
CSS
.widget {
width: 202px;
margin:100px auto;
// border:1px solid black;
padding:20px;
}
.name {
color: red;
}
.default-label {
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
width:180px;
}
.green-label {
border: 1px solid green;
padding: 10px;
margin-bottom: 10px;
width: 180px;
}
.default-input {
border: 1px solid #eaeaea;
padding: 10px;
width:180px;
}
.important-input {
border: 2px solid red;
width:180px;
}
img.center {
width: 100px;
height: 100px;
display: block;
margin: 15px auto;
}
JavaScript 1.7
/// tiny react lib start
function createElement(comp, props, ...args) {
let children = []
for(let i = 0; i< args.length;i++){
if(args[i] instanceof Array) {
children = children.concat(args[i])
} else {
children.push(args[i])
}
}
return {
nodeName: comp,
props: props || {},
children
}
}
class Component {
constructor(props) {
this.props = props
}
setState(state) {
setTimeout(() => {
this.state = state
const vnode = this.render()
let olddom = getDOM(this)
const startTime = new Date().getTime()
render(vnode, olddom.parentNode, this, olddom)
console.log("duration", new Date().getTime() - startTime)
}, 0)
}
}
function getDOM(comp) {
let rendered = comp.__rendered
while (rendered instanceof Component) { //判断对象是否是dom
rendered = rendered.__rendered
}
return rendered
}
///render
function render (vnode, parent, comp, olddom) {
let dom
if(typeof vnode == "string" || typeof vnode == "number") {
dom = document.createTextNode(vnode)
comp && (comp.__rendered = dom)
parent.appendChild(dom)
if(olddom) {
parent.replaceChild(dom, olddom)
} else {
parent.appendChild(dom)
}
} else if(typeof vnode.nodeName == "string") {
dom = document.createElement(vnode.nodeName)
comp && (comp.__rendered = dom)
setAttrs(dom, vnode.props)
if(olddom) {
parent.replaceChild(dom, olddom)
} else {
parent.appendChild(dom)
}
for(let i = 0; i < vnode.children.length; i++) {
render(vnode.children[i], dom, null, null)
}
} else if (typeof vnode.nodeName == "function") {
let func = vnode.nodeName
let inst = new func(vnode.props)
comp && (comp.__rendered = inst)
...