2017-01-16 75 views
1

我對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; 
      }, 

我留在複選框登錄在這個時候沒有做任何事情。它甚至不會讓我檢查它。

+0

什麼不是你得到些什麼?有什麼問題? –

+0

請分享此組件的類文件,因爲您正在使用受控組件。 – Xlee

+0

如果問題出在您選中的值上,您需要使用'defaultChecked'而不是'checked'。 –

回答

1

我認爲你設置狀態變量值的方式是不正確的,並且使用狀態變量來維護複選框的狀態,在輸入字段中使用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/

1

在你例子中的問題是,你硬編碼的複選框值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); 
}