javascript - Events not propagating across react components -
i have following react components:
class button extends react.component { constructor(props){ super(props); this.state = { disabled: false }; } render() { return <button disabled={this.state.disabled} onclick={this.clicked.bind(this)}>save</button>; } clicked(event) { this.setstate({disabled: true}); } } class form extends react.component { contructor(props) { super(props); this.state = { foo: "bar" }; } render() { return ( <form onsubmit={this.submit.bind(this)}> <input valuedefault={this.state.foo} /> <button /> </form> ); } submit(event) { event.preventdefault(); // stuff } }
however, when button clicked clicked method triggered submit method isn't. there way can make event propagate? there reason event isn't propagating normal html form event?
since setstate re-render entire component event stop there , cannot continue till ancestor form. instead can handle button disable in form's onsubmit. this
class button extends react.component { constructor(props){ super(props); this.state = { disabled: false }; } render() { return <button disabled={this.state.disabled}>save</button>; } clicked(event) { this.setstate({disabled: true}); } } class form extends react.component { constructor(props) { super(props); this.state = { foo: "bar" }; } render() { return ( <form onsubmit={this.submit.bind(this)}> <input valuedefault={this.state.foo} /> <button ref="button" onsubmit={this.submit.bind(this)}/> <----- added reference here </form> ); } submit(event) { event.preventdefault(); var button = this.refs.button; // <---- added ref button button.setstate({disabled: true}); <---- set disabled state button } }
here demo http://jsbin.com/ginune/edit?html,output
Comments
Post a Comment