1.受控组件写法示例(onchange因为是单向数据流)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>09_form</title>
</head>
<body>
<div id="example"></div>
<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel">
/*
需求: 自定义包含表单的组件
1. 界面如下所示
2. 输入用户名密码后, 点击登陆提示输入信息
3. 不提交表单
*/
class FormComp extends React.Component {
constructor (props) {
super(props)
// 初始化状态
this.state = {
username: 'abc',
pwd: '123'
}
}
handleNameChange = (event) => {
const username = event.target.value
// 更新状态(username)
this.setState({
username
})
}
handlePwdChange = (event) => {
const pwd = event.target.value
// 更新状态(pwd)
this.setState({
pwd
})
}
login = (event) => {
// 阻止默认行为
event.preventDefault()
const {username, pwd} = this.state
alert(`发送登陆请求 ${username}--${pwd}`)
// return false
}
render () {
const {username, pwd} = this.state
return (
<form action="/test" onSubmit={this.login}>
用户名: <input type="text" onChange={this.handleNameChange} value={username}/>
密码: <input type="password" onChange={this.handlePwdChange} value={pwd}/> /*事件在输入过程中不断触发*/
<input type="submit" value="登陆"/>
</form>
)
}
}
ReactDOM.render(<FormComp/>,document.getElementById('example'))
</script>
</body>
</html>
2.非受控组件写法示例(ref标识)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>09_form</title>
</head>
<body>
<div id="example"></div>
<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel">
/*
需求: 自定义包含表单的组件
1. 界面如下所示
2. 输入用户名密码后, 点击登陆提示输入信息
3. 不提交表单
*/
class FormComp extends React.Component {
login = (event) => {
// 阻止默认行为
event.preventDefault()
const username = this.refs.username.value
const pwd = this.refs.pwd.value
alert(`发送登陆请求 ${username}--${pwd}`)
// return false
}
render () {
return (
<form action="/test" onSubmit={this.login}>
用户名: <input type="text" ref="username"/>
密码: <input type="password" ref="pwd"/>
<input type="submit" value="登陆"/>
</form>
)
}
}
ReactDOM.render(<FormComp/>,document.getElementById('example'))
</script>
</body>
</html>