reactjs - React – the right way to pass form element state to sibling/parent elements? -
- suppose have react class p, renders 2 child classes, c1 , c2.
- c1 contains input field. i'll refer input field foo.
- my goal let c2 react changes in foo.
i've come 2 solutions, neither of them feels quite right.
first solution:
- assign p state,
state.input
. - create
onchange
function in p, takes in event , setsstate.input
. - pass
onchange
c1props
, , let c1 bindthis.props.onchange
onchange
of foo.
this works. whenever value of foo changes, triggers setstate
in p, p have input pass c2.
but doesn't feel quite right same reason: i'm setting state of parent element child element. seems betray design principle of react: single-direction data flow.
is how i'm supposed it, or there more react-natural solution?
second solution:
just put foo in p.
but design principle should follow when structure app—putting form elements in render
of highest-level class?
like in example, if have large rendering of c1, don't want put whole render
of c1 render
of p because c1 has form element.
how should it?
so, if i'm understanding correctly, first solution suggesting you're keeping state in root component? can't speak creators of react, generally, find proper solution.
maintaining state 1 of reasons (at least think) react created. if you've ever implemented own state pattern client side dealing dynamic ui has lot of interdependent moving pieces, you'll love react, because alleviates lot of state management pain.
by keeping state further in hierarchy, , updating through eventing, data flow still pretty unidirectional, you're responding events in root component, you're not getting data there via 2 way binding, you're telling root component "hey, happened down here, check out values" or you're passing state of data in child component in order update state. changed state in c1, , want c2 aware of it, so, updating state in root component , re-rendering, c2's props in sync since state updated in root component , passed along.
class example extends react.component { constructor (props) { super(props) this.state = { data: 'test' } } render () { return ( <div> <c1 onupdate={this.onupdate.bind(this)}/> <c2 data={this.state.data}/> </div> ) } onupdate (data) { this.setstate({ data }) } } class c1 extends react.component { render () { return ( <div> <input type='text' ref='myinput'/> <input type='button' onclick={this.update.bind(this)} value='update c2'/> </div> ) } update () { this.props.onupdate(this.refs.myinput.getdomnode().value) } }) class c2 extends react.component { render () { return <div>{this.props.data}</div> } }) reactdom.rendercomponent(<example/>, document.body)
Comments
Post a Comment