<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- 【包含表单的组件分类】
受控组件:表单项输入数据能自动收集成状态
非控组件:需要时才手动读取表单输入框中的数据 -->
<div id="example1"></div>
<script type="text/babel">
//1.定义组件
class App extends React.Component{
constructor(props) {
super(props)
//初始化状态
this.state = {
pwd:''
}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
handleSubmit(event){
const name = this.nameInput.value
const {pwd} = this.state
alert(`准备提交的用户名为${name},密码为${pwd}`)
//阻止事件的默认行为(提交)
event.preventDefault()
}
handleChange(event){
//读取输入的值
const pwd = event.target.value
//更新pwd的状态
this.setState({pwd})
}
render(){
return(
<form action='/test' onSubmit={this.handleSubmit}>
用户名:<input type='text' ref={input => this.nameInput=input} />
密码:<input type='password' value={this.state.pwd} onChange={this.handleChange}/>
<input type='submit' value='登录'/>
</form>
)
}
}
//2.渲染组件标签
ReactDOM.render(<App />,document.getElementById('example1'))
</script>
<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.bootcdn.net/ajax/libs/prop-types/15.7.2/prop-types.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</body>
</html>
【组件】收集表单数据
最新推荐文章于 2024-04-18 20:39:19 发布