我正在使用带有CoffeeScript的ReactJS(:
实际上我有一个处理状态的组件A.状态字段传递给子节点(在该示例中称为myChild)。孩子需要从父状态更新一些值。
我怎样才能以ReactJS的方式做到这一点?
A = React.createClass
getInitialState:
mystate: {test: 1}
render: ->
myChild {param: @state.mystate}
myChild = React.createClass
render: ->
React.DOM.div {onClick: @change}, @props.param.test
change: ->
@props.param.test += 1 # WRONG WRONG WRONG
ajax("/..../", JSON.stringify(@props.param))
.done(@onDone).fail(...)
onDone: ->
console.log "Hum..."
评论:
- @ props.param.test不能像那样改变(为了连贯性,它应该是不可变的)。
- @ props.param实际上是组件A状态内的对象,因此它应该用@setState更新,这是不可能的,因为我们在孩子中:(
如何清除这个以获得良好的ReactJS组件?
保罗?你还能救我吗? :d答案 0 :(得分:17)
父母是真相的来源,所以孩子需要告诉父母改变其状态。将父母的回调传递给孩子,并让孩子调用它。
React的文档中的communicating between components上有一个示例,可能也会有所帮助。
A = React.createClass
getInitialState: ->
mystate: {test: 1}
incrementTest: ->
@setState {mystate: {test: @state.mystate.test + 1}}
render: ->
myChild {onChange: @incrementTest, param: @state.mystate}
myChild = React.createClass
render: ->
React.DOM.div {onClick: @change}, @props.param.test
change: ->
@props.onChange
ajax("/..../", JSON.stringify(@props.param))
.done(@onDone).fail(...)
onDone: ->
console.log "Hum..."