react 表单使用
2019-12-19 本文已影响0人
未来在奋斗
只有代码
import React ,{Fragment}from 'react'
import ReactDOM from "react-dom";
// Fragment 用来代替空标签
class Cnm extends React.Component{
constructor(){
super();
this.state={
username:'',
sex:'男',
isOK:false,
fruits:["老王","老四","老六"],
myLoves: ['Apple'],
city:''
}
}
fn1 = (e) =>{
this.setState({
username: e.target.value
})
console.log(this.state.username)
}
fn2 =(e) =>{
this.setState({
sex: e.target.value
})
}
fn3=()=>{
this.setState({
isOK: !this.state.isOK
})
}
fn4=(e)=>{
let value = e.target.value
let arr =[...this.state.myLoves]
let index = arr.findIndex(item =>item ===value)
if(index > -1){
arr.splice(index,1)
}else(
arr.push(value)
)
this.setState({
myLoves:arr
})
}
fn5 =(e)=>{
this.setState({
city:e.target.value
})
}
render(){
return(
<div>
<h1>我的天</h1>
<p>普通 input 框</p>
<input type="text" value={this.state.username} onChange={this.fn1}/>
<p>单选框 radio </p>
<input type="radio" value='男' name='sex'
checked={this.state.sex==='男'}
onChange={this.fn2}
/> 男
<input type="radio" value='女' name='sex'
checked={this.state.sex==='女'} onChange={this.fn2} /> 女
<p>单个多选框 checkbox</p>
<input type="checkbox" checked={this.state.isOK} onChange={this.fn3} /> 选我选我
<p>多个多选框 checkbox</p>
{
this.state.fruits.map((item,index)=>{
return(
<Fragment key={index}>
<input type="checkbox"
value={item}
checked={this.state.myLoves.indexOf(item)> -1}
onChange={this.fn4}
/>
{item}
</Fragment>
)
})
}
<p>下拉选择框 select</p>
<select name="" value={this.state.city} onChange={this.fn5} >
<option value="" disabled>请选择</option>
{
this.state.fruits.map((item,index) =>{
return(
<option value={item} key={index}>{item}</option>
)
} )
}
</select>
</div>
)
}
}
ReactDOM.render(<Cnm>wo d tian a </Cnm>,document.getElementById('root'));