非受控組件
class Login extends React.Component{
handleSubmit = (event) =>{
event.preventDafault(); //阻止表單提交
const {username,password} = this
console.log(username.value,password.value);
}
render(){
return(
<form action="#" onSubmit={this.handleSubmit} >
用戶名:<input ref="c=>this.username =c" type="text" name="username" />
密碼:<input ref="c=>this.password=c" type="password" name="password" />
<button >登錄</button>
</form>
)
}
}
ReactDom.render(<Login/>,document.getElementById('test'))
受控組件
class Login extends React.Component{
//初始化狀態(tài)
state = {
username:'',
password:'',
}
//保存用戶名到狀態(tài)中
saveUsername = (event) =>{
console.log("change")
console.log(event.target.value)
this.setState({username:event.target.value})
}
//保存密碼到狀態(tài)中
savePassword = (event) =>{
this.setState({password:event.target.value})
}
handleSubmit = (event) =>{
event.preventDafault(); //阻止表單提交
const {username,password} = this.state
console.log(username,password);
}
render(){
return(
<form action="#" onSubmit={this.handleSubmit} >
用戶名:<input onChange={this.saveUsername} type="text" name="username" />
密碼:<input onChange={this.savePassword type="password" name="password" />
<button >登錄</button>
</form>
)
}
}
ReactDom.render(<Login/>,document.getElementById('test'))