把用户输入的值,通过setState 赋值给表单元素,这种叫做受控组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Hello extends React.Component {
state = {
inputTxt: "",
textareaTxt: "",
selectTxt: "",
isChecked: true
}
inputChange = (e) => {
this.setState({
inputTxt: e.target.value,
})
}
textareaChange = (e) => {
this.setState({
textareaTxt: e.target.value
})
}
selectChange = (e) => {
this.setState({
selectTxt: e.target.value
})
}
checkboxChange= (e) => {
this.setState({
isChecked: e.target.checked
})
}
render() {
return (
<div>
<input type="text" value={this.state.inputTxt} onChange={this.inputChange} />
<textarea cols="30" rows="10" value={this.state.textareaTxt} onChange={this.textareaChange}></textarea>
<select value={this.state.selectTxt} onChange={this.selectChange}>
<option value="西安">西安</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
</select>
<input type="checkbox" checked={this.state.isChecked} onChange={this.checkboxChange}/>
</div>
)
}
}
ReactDOM.render(<Hello />, document.getElementById('root'))
</script>
</body>
</html>