React特征学习之Form格式示例详解
Form 样式
首先来看一个简单Form, 式样如下
import * as React from 'react'; const LoginForm = () => { return ( <form> <div> // Notice: 这里要用htmlFor,相当于id <label htmlFor="email">Email</label> <input id="email" type="text" /> </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" /> </div> <button>Submit</button> </form> ); }; export { LoginForm };
屏幕显示如下
若给以上Form加入用户输入, 可引入handleSubmit指令,并设置onSubmit事件触发,具体如下
(关于用户输入View => App单向数据流,可参考相关文章 - 学习React的特征(一) - 单向数据流
import * as React from 'react'; const LoginForm = () => { // handleSubmit here const handleSubmit = (e) => { // preventDefault用于防止部分浏览器一些默认的不必要的行为 event.preventDefault(); }; return ( // onSubmit here <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email</label> <input id="email" type="text" /> </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" /> </div> <button type="submit">Submit</button> </form> ); }; export { LoginForm };
接着,进一步获取用户的输入, 可通过e.target.elements来抓取
import * as React from 'react'; const LoginForm = () => { const handleSubmit = (e) => { e.preventDefault(); // 获取input elements const email = e.target.elements.email.value; const password = e.target.elements.password.value; alert(email + ' ' + password); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email</label> <input id="email" type="text" /> </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" /> </div> <button type="submit">Submit</button> </form> ); }; export { LoginForm };
屏幕显示如下
点击Submit, 显示如下
React hook
或许用React hook更简洁优雅些 , 引入useState管理email, password状态
import * as React from 'react'; const LoginForm = () => { // Add hooks here const [email, setEmail] = React.useState(''); const [password, setPassword] = React.useState(''); const handleEmail = (e) => { setEmail(e.target.value); }; const handlePassword = (e) => { setPassword(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); alert(email + ' ' + password); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email</label> <input id="email" type="text" value={email} onChange={handleEmail} /> </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" value={password} onChange={handlePassword} /> </div> <button type="submit">Submit</button> </form> ); }; export { LoginForm };
到这里一个React Form雏形基本完成,当然Form遇到的问题远不止这些, 后续会再进一步探讨Form数据管理,验证等方案
以上就是React特征学习之Form格式示例详解的详细内容,更多关于React特征Form格式的资料请关注脚本之家其它相关文章!
相关文章
React-Native实现ListView组件之上拉刷新实例(iOS和Android通用)
本篇文章主要介绍了React-Native实现ListView组件之上拉刷新实例(iOS和Android通用),具有一定的参考价值,有兴趣的可以了解一下2017-07-07在Ant Design Pro登录功能中集成图形验证码组件的方法步骤
这篇文章主要介绍了在Ant Design Pro登录功能中集成图形验证码组件的方法步骤,这里的登录功能其实就是一个表单提交,实现起来也很简单,具体实例代码跟随小编一起看看吧2021-05-05
最新评论