在reactjs我想让按钮让用户保持登录状态
问题描述:
我对reactjs很新颖,我试图添加一个带有“保持登录状态”复选框的表单。这是我的设置,但我没有得到我想要的结果。将不胜感激任何帮助。谢谢在reactjs我想让按钮让用户保持登录状态
<Input
type="email"
name="email"
value={this.state.signInForm.email}
placeholder="Email"
onChange={this.handleSigninChange} />
<Input
type="password"
name="password"
value={this.state.signInForm.password}
placeholder="Password"
onChange={this.handleSigninChange} />
<Input
type="checkbox"
name="save_login_state"
label="Keep me signed in"
checked={false}
onChange={this.handleLoggedInState.bind(this)} />
handleLoggedInState: function() {
this.state.signInForm.email = true;
},
我留在复选框登录在这个时候没有做任何事情。它甚至不会让我检查它。
答
我认为你设置状态变量值的方式是不正确的,并且使用状态变量来维护复选框的状态,在输入字段中使用I
而不是它应该是i
(if您使用的是默认的输入元素),试试这个:
handleLoggedInState: function() {
this.setState({checkboxValue: !this.state.checkboxValue});
},
<input
type="checkbox"
name="save_login_state"
label="Keep me signed in"
checked={this.state.checkboxValue}
onChange={this.handleLoggedInState.bind(this)} />
检查jsFiddle
的工作例如:https://jsfiddle.net/xep3mskr/
答
在你例子中的问题是,你硬编码的复选框值false
。试试这个:
<input
type="checkbox"
name="save_login_state"
label="Keep me signed in"
checked={this.state.saveLoginState}
onChange={this.toggleLoginState.bind(this)}
/>
toggleLoginState: function() {
this.setState({saveLoginState: !this.state.saveLoginState});
}
此外,你应该总是绑定你的函数的构造函数。
e.g
constructor(props) {
super(props);
// bind your component functions in the constructor
this.toggleLoginState = this.toggleLoginState.bind(this);
}
什么不是你得到些什么?有什么问题? –
请分享此组件的类文件,因为您正在使用受控组件。 – Xlee
如果问题出在您选中的值上,您需要使用'defaultChecked'而不是'checked'。 –