Skip to content

Instantly share code, notes, and snippets.

@huzidaha
Last active February 23, 2017 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huzidaha/bcf68914d453c6946c8f45ac59638d84 to your computer and use it in GitHub Desktop.
Save huzidaha/bcf68914d453c6946c8f45ac59638d84 to your computer and use it in GitHub Desktop.
React.js in 40 Lines.js
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)
}
}
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