i have span in child component displays status text:
class loginform extends react.component { constructor(props) { super(props); this.state = { status: "" }; this.login = this.login.bind(this); this.setstatus = this.setstatus.bind(this); } login() { if (this.validfields()) { ... } } validfields() { let isvalid = true; let username = $("#username").val().trim(); let password = $("#password").val().trim(); let error = ""; if (username === "") { error = "please enter username."; isvalid = false; } else if (password === "") { error = "please enter password."; isvalid = false; } this.setstatus(error); return isvalid; } setstatus(status) { this.setstate({ status: status }); } render() { return ( <div classname="form"> <input type="text" name="username" id="username" placeholder="username" required /> <input type="password" name="password" id="password" placeholder="password" required /> <button type="submit" onclick={this.login}>log in</button> <span classname="login-msg">{this.state.status}</span> </div> ); } }
when user clicks button , textbox empty, displays error message. actual login method in parent component , when login fails, want state.status if child updated.
the parent looks this:
class indexcontainer extends react.component { constructor(props) { super(props); this.state = { loginstatus: "" }; this.login = this.login.bind(this); } login(companycode, username, password) { var logindata = { ... }; fetch("/account/login", { ... }).then((response) => { response.json().then((data) => { if (data.success) { window.location.href = data.returnurl; } else { this.setstate({ loginstatus: data.errormessage }); } }); }).catch(function (err) { console.log(err); }); } render() { return ( <browserrouter> <route path="/account/login" exact render={() => <loginform login={this.login} status={this.state.loginstatus} /> } /> </browserrouter> ); } }
the parent passes loginstatus message child child's props.status. want status , put in state.status of child can't figure out do.
in react, can use componentwillreceiveprops()
update state whenever component gets new props.
you can read this document more information.
https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops
Comments
Post a Comment