demo1: 在输入框中输入或者删除数据时,能够实时监控。react
class App extends React.Component {
state = {
val : ""
}
handleChange = (e) => {
this.setState({
val : e.target.value
})
}
render(){
return (
<div>
<h1>form</h1>
<input
type="text"
value={this.state.val}
onChange={this.handleChange}
/>
<b>{this.state.val}</b>
</div>
)
}
}
ReactDOM.render(
<App></App>,
document.getElementById("app")
)
复制代码
初始效果: bash
demo2:单选框,下拉列表,多选框,文本域的一些操做app
class App extends React.Component {
state = {
user : "",
sex : "",
cityList : ["上海","江苏","浙江"],
city : "" ,
like : [
{
title: "篮球",
checked: true
},
{
title: "足球",
checked: false
},
{
title: "乒乓球",
checked: false
}
],
textArea : ""
}
//提交数据
handleSubmit = (e) => {
e.preventDefault(); //阻止默认事件
console.log("用户名",this.state.user);
console.log("性别",this.state.sex);
console.log("城市",this.state.city);
console.log("爱好",this.state.like);
console.log("介绍",this.state.textArea);
}
//更新用户名
handleUser = (e) => {
this.setState({
user : e.target.value
})
}
//更新单选框
handleSex = (e) => {
this.setState({
sex : e.target.value
})
}
//更新下拉菜单
handleSelect = (e) => {
this.setState({
city : e.target.value
})
}
//更新多选框
handleLike = (i) => {
const like = this.state.like;
like[i].checked = !like[i].checked
this.setState({
like
})
}
//处理文本域
handleText = (e) => {
this.setState({
textArea : e.target.value
})
}
render(){
return (
<div>
<h1>form</h1>
<br/>
<form onSubmit={this.handleSubmit}>
用户名:<input type="text" value={this.state.user} onChange={this.handleUser}/>
<br/>
<br/>
性别:
<input type="radio" value={"0"} checked={this.state.sex === "0"} onChange={this.handleSex} /> 男
<input type="radio" value={"1"} checked={this.state.sex === "1"} onChange={this.handleSex} /> 女
<br/>
<br/>
城市:
{
this.state.cityList.length>0 && (
<select value={this.state.city} onChange={this.handleSelect}>
{
this.state.cityList.length>0 && this.state.cityList.map((item, index) => {
return(
<option key={index}>{item}</option>
)
})
}
</select>
)
}
<br/>
爱好:
{
this.state.like.length>0 && this.state.like.map((item, index) => {
return (
<div key={index}>
<input
type={"checkbox"}
checked={item.checked}
onChange={this.handleLike.bind(this, index)}
/>
{item.title}
</div>
)
})
}
<br/>
<textarea value={this.state.textArea} onChange={this.handleText} cols={"30"} ></textarea>
<br/>
<br/>
<input type="submit" value={"提交"}/>
</form>
</div>
)
}
}
ReactDOM.render(
<App></App>,
document.getElementById("app")
)
复制代码
效果图,将传递给后台的数据打印出来: ui