Last active
February 23, 2017 08:36
-
-
Save huzidaha/bcf68914d453c6946c8f45ac59638d84 to your computer and use it in GitHub Desktop.
React.js in 40 Lines.js
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 createDOMFromString = (domString) => { | |
const div = document.createElement('div') | |
div.innerHTML = domString | |
return div | |
} | |
class Component { | |
constructor (props = {}) { | |
this.props = props | |
} | |
setState (state) { | |
const oldEl = this.el | |
this.state = state | |
this.el = this.renderDOM() | |
if (this.onStateChange) this.onStateChange(oldEl, this.el) | |
} | |
renderDOM () { | |
this.el = createDOMFromString(this.render()) | |
if (this.onClick) { | |
this.el.addEventListener('click', this.onClick.bind(this), false) | |
} | |
return this.el | |
} | |
} | |
const mount = (wrapper, component) => { | |
wrapper.appendChild(component.renderDOM()) | |
component.onStateChange = (oldEl, newEl) => { | |
wrapper.insertBefore(newEl, oldEl) | |
wrapper.removeChild(oldEl) | |
} | |
} |
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
class LikeButton extends Component { | |
constructor (props) { | |
super(props) | |
this.state = { isLiked: false } | |
} | |
onClick () { | |
this.setState({ | |
isLiked: !this.state.isLiked | |
}) | |
} | |
render () { | |
return ` | |
<button class='like-btn'> | |
<span class='like-text'>${this.props.word || ''} ${this.state.isLiked ? '取消' : '点赞'}</span> | |
<span>👍</span> | |
</button> | |
` | |
} | |
} | |
class RedBlueButton extends Component { | |
constructor (props) { | |
super(props) | |
this.state = { | |
color: 'red' | |
} | |
} | |
onClick () { | |
this.setState({ | |
color: 'blue' | |
}) | |
} | |
render () { | |
return ` | |
<div style='color: ${this.state.color};'>${this.state.color}</div> | |
` | |
} | |
} | |
mount(wrapper, new LikeButton()) | |
mount(wrapper, new LikeButton()) | |
mount(wrapper, new RedBlueButton()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment