react表单的写法
import React, { Component } from 'react'
export default class two extends Component {
state = {
value: "123",
inputValue: "1234",
checkData: [],
radioData: "",
selectData: ""
}
// input文本框
handleChange = (e) => {
this.setState({
inputValue: e.target.value
})
}
// 单选框
radioChange = (event) => {
console.log(event.target.value)
this.setState({
radioData: event.target.value
});
}
// 多选框
checkChange = (e) => {
console.log(e.target.value)
let item = e.target.value;
let items = this.state.checkData.slice()
let index = items.indexOf(item);
index === -1 ? items.push(item) : items.splice(index, 1);
this.setState({ checkData: items });
console.log(items)
}
// 下拉列表
SelectChange = (e) => { // 选择
this.setState({
selectData: e.target.value
})
}
handleSubmit = (e) => {
alert('你提交的内容为' + JSON.stringify(this.state));
e.preventDefault(); // 阻止默认行为,在提交之前需要验证的时候先拦截一下
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>文本框: <input value={this.state.value} onChange={(e) => { this.setState({ value: e.target.value }) }}></input></label><br />
<label>文本框: <input value={this.state.inputValue} onChange={this.handleChange}></input></label><br />
<label>单选框: <input type="radio" name='gender' value="Man"
onChange={this.radioChange} />男
<input type="radio" name='gender' value="Men"
onChange={this.radioChange} />女</label><br />
<label>爱吃的水果:<input type="checkbox" name="fruit" value="apple"
onChange={this.checkChange} />apple</label>
<input type="checkbox" name="fruit" value="banana"
onChange={this.checkChange} />banana
<input type="checkbox" name="fruit" value="pear"
onChange={this.checkChange} />pear
<label>你喜欢的水果是:</label>
<select onChange={this.SelectChange}>
<option value="未选择">请选择</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="orange">orange</option>
</select>
<input type="submit" value="提交" />
</form>
</div>
)
}
}