2016-05-17 58 views
14

我試圖在反應中實現簡單的註冊頁面。但是,當我嘗試提交表單時,我得到了signup.js:53 Uncaught TypeError: Cannot read property 'state' of null未捕獲的類型錯誤:無法讀取null中的屬性「狀態」反應

顯然反應並未正確設置狀態。這裏是註冊組件的代碼:

import'react'中的{Component};

export default class Signup extends Component { 

    constructor(props) { 
    super(props) 
    this.state = { 
     username: "", 
     password1: "", 
     password2: "", 
     error: "" 
     } 
    this.onChange = this.onChange.bind(this); 
    } 

    onChange(e) { 
    this.setState({[e.target.name]: e.target.value}) 
    } 

    handleSubmit(e) { 
    e.preventDefault() 
    console.log(e) 
    var username = this.state.username.trim() 
    var password1 = this.state.password1.trim() 
    var password2 = this.state.password2.trim() 

    if (!username || !password1 || !password2) 
     return 
    else if (password2 !== password1) 
     this.setState({ 
     error: "Passwords didn't match", 
     username: "", 
     password1: "", 
     password2: "" 
     }) 
    } 
    render() { 
    return (
     <div> 
     <form className="signupForm" onSubmit={this.handleSubmit}> 
      <input 
      type="text" 
      name="username" 
      placeholder="Username" 
      value={this.state.username} 
      onChange={this.onChange} /> 
      <input 
      type="text" 
      name="password1" 
      placeholder="Password" 
      value={this.state.password1} 
      onChange={this.onChange} /> 
      <input 
      type="text" 
      name="password2" 
      placeholder="Password again" 
      value={this.state.password2} 
      onChange={this.onChange} /> 
      <input type="submit" value="Post" /> 
     </form> 
     <div value={this.state.error}></div> 
     </div> 
    ) 
    } 
} 

回答

34

應設置爲this作爲handleSubmit你爲onChange

constructor(props) { 
    super(props) 
    this.state = { 
    username: "", 
    password1: "", 
    password2: "", 
    error: "" 
    } 
    this.onChange = this.onChange.bind(this); 
    this.handleSubmit = this.handleSubmit.bind(this); 
} 
相關問題