一、单选
App.js
import React,{Component} from "react"
class App extends Component{
constructor(){
super();
this.state={
radioVal:'男'
}
}
render(){
let {radioVal}=this.state
return (
<div>
<p>
男:<input type="radio" value="男" onChange={this.handelRadio.bind(this)} checked={radioVal==="男"}/>
</p>
<p>
女:<input type="radio" value="女" onChange={this.handelRadio.bind(this)} checked={radioVal==="女"}/>
</p>
<p>您选择的性别是----{radioVal}</p>
</div>
)
}
handelRadio(e){
let val = e.target.value
this.setState({
radioVal:val
})
}
}
export default App
二、多选
App.js
import React,{Component} from "react"
class App extends Component{
constructor(){
super();
this.state={
checkVal:[]
}
}
render(){
let {checkVal} = this.state
return(
<div>
<p>
<input type="checkbox" value="sun" onChange={this.handelCheckbox.bind(this)} />sun
</p>
<p>
<input type="checkbox" value="moon" onChange={this.handelCheckbox.bind(this)} />moon
</p>
<p>
<input type="checkbox" value="star" onChange={this.handelCheckbox.bind(this)} />star
</p>
{/* 复杂数据类型如果数据发生了改变 不会自动进行遍历*/} <------这是jsx的注释方式
<p>您选择的爱好为:{checkVal.map((item,index)=>{
return <li key={index}>{item}</li>
})}</p>
</div>
)
}
handelCheckbox(e){
let val = e.target.value
let arr = this.state.checkVal
let bstop = arr.includes(val)
if(bstop){
let index = arr.indexOf(val)
arr.splice(index,1)
}else{
arr.push(val)
}
this.setState({
checkVal:arr
},()=>{
console.log(this.state.checkVal)
})
}
}
export default App
三、下拉菜单
APP.js
import React,{Component} from "react"
class App extends Component{
constructor(){
super();
this.state={
selectVal:""
}
}
render(){
let {selectVal} = this.state
return(
<div>
<select defaultValue={selectVal} onChange={this.handleSelectChange.bind(this)}>
<option value="请选择">请选择</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
</select>
<p>您选择的时间为:{selectVal}</p>
</div>
)
}
handleSelectChange(e){
let val = e.target.value
this.setState({
selectVal:val
})
}
}
export default App