Frage

I'm using ReactJS with CoffeeScript (:

Actually I have a component A which handle a state. A state field is passed to the child (called myChild in that example). The child needs to update some value from the parent state.

How can I do that in the ReactJS way ?

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..."

Comments:

-@props.param.test can't be changed like that (for coherence and it's should be immutable).

-@props.param is in fact the object inside the state of component A, thus it should be updated with @setState which is not possible since we are in the child :(

How can I clear this to have a good ReactJS component ?

Paul ? Will you still help me ? :D

War es hilfreich?

Lösung

The parent is the source of truth, so the child needs to tell the parent to change its state. Pass a callback from the parent to the child, and have the child call it.

There's an example on communicating between components in React's docs that might be helpful too.

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..."
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top