单向数据绑定
1.在constructor里注册数据
constructor(){
super();
this.title="注册"
}
2.使用{}进行数据绑定
<h3>{this.title}</h3>
双向数据绑定
1.在constructor里用this.state注册数据
constructor(){
super();
this.state={
user:"",
pass:"",
loginSuccess:false
}
}
2.使用onChange事件监听数据变化并赋值给this.state
handeChange(item,event){
for(let StateItem in this.state){
if(item===StateItem){
this.state[item]=event.target.value;
this.setState(this.state)
}
}
}
<div className="input-box">
<label htmlFor="" >用户名</label><input type="text" onChange={this.handeChange.bind(this,"user")} value={this.state.user}/>
</div>
<div className="input-box">
<label htmlFor="">密码</label><input type="password" onChange={this.handeChange.bind(this,"pass")} value={this.state.pass}/>
</div>
最后,贴出最终代码
import '../login/login.css';
import './register.css';
class Register extends Component{
constructor(){
super();
this.title="注册"
this.state={
user:"",
pass:"",
loginSuccess:false
}
}
handeChange(item,event){
for(let StateItem in this.state){
if(item===StateItem){
this.state[item]=event.target.value;
this.setState(this.state)
}
}
}
render(){
return (
<div className="Register">
<div className="login-box">
<h3>{this.title}</h3>
<p></p>
<div className="input-box">
<label htmlFor="" >用户名</label><input type="text" onChange={this.handeChange.bind(this,"user")} value={this.state.user}/>
</div>
<div className="input-box">
<label htmlFor="">密码</label><input type="password" onChange={this.handeChange.bind(this,"pass")} value={this.state.pass}/>
</div>
<div style={{textAlign:'center'}}>
<button className="login-btn">注册</button>
</div>
</div>
</div>
);
}
}
export default Register;