Skip to content

Instantly share code, notes, and snippets.

@DC3
Created August 15, 2017 07:01
Show Gist options
  • Save DC3/0dbfd82cf1c13d490ad53b5532d14424 to your computer and use it in GitHub Desktop.
Save DC3/0dbfd82cf1c13d490ad53b5532d14424 to your computer and use it in GitHub Desktop.
React Two-way bindings
React = @React or require? 'react'
win = window
doc = win.document
# 业务逻辑变为 Mixin 方便复用
Mixin1 =
getInitialState: ->
title: @props.title
name: ''
count: 0
componentDidMount: ->
@_tId = setInterval @updateCount, @props.time || 100
componentWillMount: ->
clearInterval @_tId
updateCount: ->
#@setState count: @state.count++ # 这里会失败 因为 @state.count 不可变
@setState count: @state.count+1 # 一旦 setState 自动渲染
render: ->
{title, name, count} = @state
@div null,
@h2, null, title
@input valueLink: @linkState('name')
@div null,
@p null, "output: #{name}"
@p null, "count: #{count}"
@div null,
@p null, "如果有 children 则在下面"
@props.children
# 1 Coffee Class way
class Example extends React.Component
mixins: [React.addons.LinkedStateMixin, React.DOM, Mixin1]
Example1 = Example.build()
# 2 React.createClass way
Example2 = React.createFactory React.createClass
mixins: [React.addons.LinkedStateMixin, React.DOM, Mixin1]
class Button extends React.Component
mixins: [React.DOM]
render: ->
@button null, '我是个按钮1'
Button1 = Button.build()
class Box extends React.Component
mixins: [React.DOM]
render: ->
@div null,
@button null, '我是个按钮2'
'我是个Box1' # 如果直接是字符串 会自己 wrap span
Box1 = Box.build() # toComponent 别名
win.onload = ->
win.app1 = React.render Example1({
title: 'Two Way Binding Title: '
time: 500
}, Button1()), doc.getElementById('main1')
win.app2 = React.render Example2({
title: 'Two Way Binding Title: '
time: 1000
}, Button1(), Box1()), doc.getElementById('main2')
doctype html
html(lang="zh-cn")
head
title React Two-Way Binding Example
body
h1 Example1:
div#main1
hr
h1 Example2:
div#main2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment