import React, { Component } from 'react';
let defaultValue = {
username: '1111',
password: "",
sex: "1", // 1男 0 是女
ah: ['足球'],
city: "咸阳",
lovecity: [],
desc: ""
}
class App extends Component {
constructor(){
super();
this.state ={
reginfo:{
...defaultValue
},
love:['篮球','足球','羽毛球','铅球'],
citylist:['北京','上海','西安','咸阳','阿房宫']
}
}
// 单行文本框、多行文本框、单选
singleChange(attr,e){
console.log(attr)
console.log(e.target.value)
let newval = e.target.value;
this.setState(state=>({
reginfo:{
...state.reginfo,
[attr]: newval
}
}))
}
// 多选、下拉
multipleChange(attr,e){
console.log(e.target.value)
let newval = e.target.value;
let oldarr = this.state.reginfo[attr];
let idx = oldarr.indexOf(newval);
console.log(idx)
if (idx===-1){
oldarr.push(newval)
}else{
oldarr.splice(idx,1)
}
this.setState(state => ({
reginfo: {
...state.reginfo,
[attr]: oldarr
}
}))
}
submit(){
console.log(this.state.reginfo)
}
reset(){
this.setState({
reginfo:{
...defaultValue
}
})
}
render() {
let reginfo = this.state.reginfo;
return (
<div>
<p>姓名: <input type="text" value={reginfo.username} onChange={this.singleChange.bind(this,'username')} /> {reginfo.username} </p>
<p>密码: <input type="password" value={reginfo.password} onChange={this.singleChange.bind(this, 'password')} /> {reginfo.password} </p>
<p>性别:
<input type="radio" id="man" value="1" checked={reginfo.sex === "1"} onChange={this.singleChange.bind(this,'sex')} />
<label htmlFor="man">男</label>
<input type="radio" id="woman" value="0" checked={reginfo.sex === "0"} onChange={this.singleChange.bind(this, 'sex')} />
<label htmlFor="woman">女</label>
{reginfo.sex}
</p>
<p>
爱好:{
this.state.love.map((val,idx)=>{
return (
<label key={idx}><input type="checkbox" checked={ reginfo.ah.includes(val) } value={val} onChange={ this.multipleChange.bind(this,'ah') } />{val}</label>
)
})
}
{JSON.stringify(reginfo.ah)}
</p>
<p>
家乡:
<select onChange={this.singleChange.bind(this, 'city')} value={reginfo.city} >
<option value="">==请选择==</option>
{
this.state.citylist.map((val, idx) => {
return (
<option key={idx} value={val}>{val}</option>
)
})
}
</select>
{reginfo.city}
</p>
<p>
想去的地方:
<select onChange={this.multipleChange.bind(this, 'lovecity')} value={reginfo.lovecity} multiple size="5">
{
this.state.citylist.map((val, idx) => {
return (
<option key={idx} value={val}>{val}</option>
)
})
}
</select>
{JSON.stringify(reginfo.lovecity)}
</p>
<p>
<textarea value={reginfo.desc} onChange={this.singleChange.bind(this, 'desc')}></textarea>
{reginfo.desc}
</p>
<button onClick={ this.submit.bind(this) }>提交</button>
<button onClick={this.reset.bind(this)}>重置</button>
</div>
);
}
}
React原生表单相关知识
最新推荐文章于 2022-07-30 16:50:43 发布