表单技术
React
中的表单元素大都基于一种受控组件
的技术来实现交互
Form
表单中,input/textarea/selectbox
都是基于 value
显示值,onChange
响应事件
checkbox/radio
也是 onChange
响应事件,value
显示值,不同的是使用 checked
判断是否选中
input=file
由于只有只读属性,故是一个非受控组件,在后面的章节会提及到
- 受控组件需要为每个方式都编写一个事件处理,并且通过一个组件 state 来管理状态
- 这在某些情况下会变得异常繁琐,这时候可以看看非受控组件:
https://react.docschina.org/docs/uncontrolled-components.html
class ReactForm extends Component {
constructor (props) {
super(props)
this.state = {
name: '',
male: '',
introduce: '',
weight: 'fat',
sport: 'basketball'
}
}
handleChange = (e) => {
const name = e.target.name
const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value
this.setState({
[name]: value
})
}
render () {
const s = this.state
const hc = this.handleChange
const he = s.male ? 'he' : 'she'
const his = s.male ? 'his' : 'her'
return (
<div className={'react-comp'}>
<div>{s.name} is {s.male ? 'male' : 'female'} and {he} is a {s.introduce}</div>
<div>{he} is {s.weight} and {his} favorite sport is {s.sport}</div>
<label>
Name: <input type="text" placeholder='名字' name='name' value={s.name} onChange={hc}/>
</label>
<label>
Male: <input type="checkbox" name='male' value={s.male} onChange={hc}/>
</label>
<label>
Introduce:
<textarea name="introduce" cols="30" rows="3" value={s.introduce} onChange={hc}></textarea>
</label>
<label>
Weight:
<select name="weight" id="" onChange={hc} value={s.weight}>
<option value="fat">fat</option>
<option value="thin">thin</option>
<option value="normal">normal</option>
</select>
</label>
<label htmlFor="">
<label><input name="sport" type="radio" value="basketball" onChange={hc} checked={s.sport==='basketball'}/>篮球</label>
<label><input name="sport" type="radio" value="badminton" onChange={hc} checked={s.sport==='badminton'}/>羽毛球</label>
<label><input name="sport" type="radio" value="swimming" onChange={hc} checked={s.sport==='swimming'}/>游泳</label>
</label>
</div>
)
}
}