如何显示已存在的电子邮件ID'消息使用React.js?
我已检查过' email-id已存在'在后端的条件。但我不明白如何在文本框附近显示该消息。
我试图在警报中显示该消息。
以下是注册表格:
var RegistrationForm = React.createClass({
//get initial state enent
getInitialState : function(){
return {
strFullName : '',
strEmail:'',
strPassword : '',
Fields : [],
intPhoneNumber:''
}
},
// submit function
handleSubmit : function(e){
e.preventDefault();
//Validate entire form here
var validForm = true;
this.state.Fields.forEach(function(field){
if (typeof field.isValid === "function") {
var validField = field.isValid(field.refs[field.props.name]);
console.log("validField "+validField);
validForm = validForm && validField;
}
});
console.log("form"+validForm);
//after validation complete post to server
if (validForm) {
alert("ok");
//pass data to server
axios.post("/register",
{
full_name :this.state.strFullName,
email:this.state.strEmail,
password:this.state.strPassword,
phone_number:this.state.intPhoneNumber,
}).then(function (response) {
var data=response.data;
alert("Email already exist");
});
}
this.setState({
strFullName:'',
strEmail:'',
intPhoneNumber:'',
strPassword:''
})
},
render : function(){
//Render form
return(
<MyInput type={'email'}
value={this.state.strEmail}
label={'Email'}
name={'Email'}
htmlFor={'Email'}
isrequired={true}
onChange={this.onChangeEmail}
onComponentMounted={this.register}
strMessageRequired={'Please Enter Email.'}
strMessageEmail={'Please Enter Correct Email'} />
);
}
});
module.exports=RegistrationForm;
MyInput Component用于验证。 MyInput.jsx
var React = require('react');
var MyInput = React.createClass({
//onchange event
handleChange: function (e) {
this.props.onChange(e.target.value);
var isValidField = this.isValid(e.target);
},
//validation function
isValid: function (input) {
if (input.getAttribute('type') == "email" && input.value != "") {
if (!this.validateEmail(input.value)) {
input.classList.add('error');
input.nextSibling.textContent = this.props.strMessageEmail;
return false;
}
else {
input.classList.remove('error');
input.nextSibling.textContent = "";
}
}
return true;
},
答案 0 :(得分:0)
if (validForm) {
alert("ok");
var self=this; // put
.
.
.
.
//instead of alert
this.setState({
error:'Email Already exists'
})
这将呈现父组件,然后呈现MyInput组件。 然后,您需要将此作为支持传递给子组件。
<MyInput type={'email'}
value={this.state.strEmail}
label={'Email'}
name={'Email'}
htmlFor={'Email'}
isrequired={true}
onChange={this.onChangeEmail}
onComponentMounted={this.register}
strMessageRequired={'Please Enter Email.'}
strMessageEmail={'Please Enter Correct Email'}
error={this.state.error || null} //new addition
/>
这会使MyInput呈现另一个道具,即错误&#39;
现在,在MyInput的render方法中,您可以像:
一样处理它if(!this.props.error){
return (<div className="message">{this.props.error}</div>
}
或者如果要在两者之间显示内容,请使用反应条件渲染。
在输入框上方或下方添加此行
{this.props.error > 0 &&
<h2>
{this.props.error}
</h2>
}