| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 
 | import React, { Component } from "react";
 export default class TableDemo extends Component {
 state = {
 value1: "",
 value2: "",
 };
 onClickSubmit = (e) => {
 e.preventDefault();
 console.log(this.state);
 };
 onChange = (e) => {
 const name = e.target.name;
 console.log(name);
 switch (name) {
 case "value1":
 this.setState({
 value1: e.target.value.toUpperCase(),
 });
 break;
 case "value2":
 // 第一种解决方案
 // this.setState({
 //   value2: e.target.value.replace(/[^\d]/g, ""),
 // });
 // 第二种解决方案
 const newVal = e.target.value
 .split("")
 .map((item) => {
 if (!isNaN(item)) {
 return item;
 }
 return "";
 })
 .join("");
 this.setState({
 value2: newVal,
 });
 break;
 default:
 break;
 }
 };
 render() {
 return (
 <>
 <h1>受控表单DEMO</h1>
 <form>
 <input
 type="text"
 value={this.state.value1}
 name="value1"
 onChange={this.onChange}
 placeholder="自动转换大写"
 style={{ display: "block", padding: "10px", margin: "10px" }}
 />
 <input
 type="text"
 value={this.state.value2}
 name="value2"
 onChange={this.onChange}
 placeholder="只能输入数字"
 style={{ display: "block", padding: "10px", margin: "10px" }}
 />
 <button
 onClick={this.onClickSubmit}
 style={{
 display: "block",
 padding: "10px",
 margin: "10px",
 backgroundColor: "black",
 borderRadius: "5px",
 color: "#fff",
 border: "none",
 cursor: "pointer",
 }}
 >
 提交
 </button>
 </form>
 </>
 );
 }
 }
 
 
 |