我为这个简单的问题感到非常抱歉,但实际上我的大脑现在无法正常工作,如何通过反应来验证输入内容?
这是我的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;
请帮助我进行验证。
我只需要检查值是否不为空,如果值为空,则将输入边框的颜色更改为红色!
答案 0 :(得分:3)
为此,我认为最好创建React.component来将表单的状态保存到其中,并在提交时获取状态并验证其值。我建议您使用一些验证库,例如joi-browser或validator
类似这样的东西
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 )
}
}
希望它会有所帮助:)
答案 1 :(得分:0)
import React, { Component } from 'react';
class MyComponent extends Component {
nameRef = React.createRef();
passwordRef = React.createRef();
//within your constructor
this.state = {
uname: '',
err: '',
psw: '',
}
handleSubmit = (event) => {
event.preventDefault();
const nameRefValue = this.nameRef.value.value;
const passwordRefValue = this.passwordRef.value.value;
if((nameRefValue.length > 0) || (passwordRefValue.length > 0)) {
this.setState({
uname: this.nameRefValue,
psw: this.passwordRefValue,
});
}
else {
this.handleError(error);
}
}
handleError = (error) => {
this.setState({
err: error,
});
}
render = () => {
return (
//your form
//add ref attribute to each form input
//call this.handleSubmit on onSubmit event
//show the span containing the error and apply the error class
)
}
export default MyComponent;