1.代码
<body>
<div id="test"></div>
<script type="text/babel">
"use strict";
class Login extends React.Component {
handleSubmit=(event)=>{
event.preventDefault();
const{username,password}=this;
alert(`你输入的用户名是:${this.username.value},你输入的密码是:${this.password.value}。`);
}
render() {
return (
<form action="https://www.baidu.com" onSubmit={this.handleSubmit}>
用户名:
<input
ref={(c) => (this.username = c)}
type="text"
name="username"
/>
密码:
<input
ref={(c) => (this.password = c)}
type="password"
name="password"
/>
<button>登录</button>
</form>
);
}
}
ReactDOM.render(<Login />, document.getElementById("test"));
</script>
</body>
2.代码讲解
- 通过回调函数方式将username和password绑定到this中
- 通过event的preventDefault方法,阻止网页跳转
- 通过反引号字符拼接,弹出提示框
3.运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/675ee556dc37cbdfec943358102d0674.png)