javascript - 如何使用 reactjs 验证我的表单元素?
问题描述
对于这个简单的问题,我真的很抱歉,但我的大脑现在真的不能工作,我怎样才能通过反应来验证我的输入?
这是我的 index.js
import React from 'react';
import './style.scss';
const MyComponent = () => (
<div style={{margin:'auto', float:'none'}}>
<table cellSpacing="0" cellPadding="0" style={{margin:'0 auto',marginBottom:'2rem'}}>
<thead>
<tr>
<td>
<span
style={{
height: '100px',
width: '100px',
backgroundColor: 'darkgrey',
borderRadius: '50%',
display: 'inline-block'
}}/>
</td>
<td style={{color:'#2c4e88'}}>
<h1><p>swedavia</p></h1>
<h2><p>swedish airports</p></h2>
</td>
</tr>
</thead>
</table>
<form>
<div style={{color:'darkgrey',padding: '16px'}}>
<label htmlFor="uname">Username</label>
<input type="text" name="uname" required/>
<label htmlFor="psw">Password</label>
<input type="password" name="psw" required/>
<div style={{marginTop:'2rem'}}>
<button type="submit">ОТПРАВИТЬ</button>
<span style={{float: 'right',paddingTop: '16px'}}><a href="#">Forgot password?</a></span>
</div>
</div>
</form>
</div>
);
export default MyComponent;
请帮助我创建该验证。
我只需要检查值是否不为空,如果值为空,则将输入边框的颜色更改为红色!
解决方案
为此,我想最好创建 React.component 以将表单的状态保存到其中,并在提交时获取状态并验证它的值。我建议您使用一些验证库,例如joi-browser或验证器
像这样的东西
import React from 'react';
import './style.scss';
class MyComponent extends React.Component {
// initial state
state = {
username : { val: "", err : "" },
// ... etc
}
handleInputChange (e) {
// your logic for input change
// you can even including "pre-validation" in this step
const val = e.target.value;
this.setState({ username: { val, err: "" } })
}
handleSubmit = () => {
const { username, password } = this.state
// better to validate password and login with some library, this is just an example
// you should reset value of input on error and
// add `err`..err should be handled in your template where it should be shown
if ( !username.length ) this.setState({ username: { val: "", err: "Please fill this field" } })
//...submit stuff
}
render = () => {
return ( // your template )
}
}
希望能帮助到你 :)
推荐阅读
- javascript - 每秒添加课程,但仅持续 5 秒。[JavaScript]
- java - 如何将 SQS 大型消息处理与 Gradle 一起用于我的 AWS Lambda 函数?
- git - Docker,从 git repo 安装 pip 找不到 git
- npm - Gatsby 开发命令不起作用,显示 TypeError: is.urlInstance is not a function
- sql - 如何根据 SQL 列生成动态产品描述?
- pagination - 如何在 Api 上实现分页并一次只获取一些数据块
- java - 尝试打开项目时获取“项目文件夹已包含 NetBeans 项目”
- python - Jupyter 绘制了意想不到的数字
- powershell - 带有特殊字符的字符串连接
- github - 是否可以仅撤销 GitHub 中 VSCode 的特定权限而不是全部访问权限?