मैं हल्के वजन समाधान का उपयोग कर रहा हूं और यह बहुत अनुकूलन योग्य है।
इनपुट onChange
पर मान्य है लेकिन किसी भी पर बदला जा सकता है। हम textarea, चेकबॉक्स, रेडियो
var Input = React.createClass({
getInitialState: function(){
// we don't want to validate the input until the user starts typing
return {
validationStarted: false
};
},
prepareToValidate: function(){},
_debounce: function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
},
componentWillMount: function(){
var startValidation = function(){
this.setState({
validationStarted: true
})
}.bind(this);
// if non-blank value: validate now
if (this.props.value) {
startValidation();
}
// wait until they start typing, and then stop
else {
this.prepareToValidate = _self._debounce(startValidation, 1000);
}
},
handleChange: function(e){
if (!this.state.validationStarted) {
this.prepareToValidate();
}
this.props.onChange && this.props.onChange(e);
},
render: function(){
var className = "";
if (this.state.validationStarted) {
className = (this.props.valid ? 'Valid' : 'Invalid');
}
return (
<input
{...this.props}
className={className}
onChange={this.handleChange} />
);
}
});
हमारे घटक जहां हम फॉर्म प्रस्तुत करने जा रहे हैं के लिए समान घटक बना सकते हैं। हम
var App = React.createClass({
getInitialState: function(){
return {email: ""};
},
handleChange: function(e){
this.setState({
email: e.target.value
})
},
validate: function(state){
return {
email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/.test(state.email)
}
},
render: function(){
var valid = this.validate(this.state);
return (
<div>
<Input valid={valid.email}
value={this.state.email}
onChange={this.handleChange}
placeholder="[email protected]"/>
</div>
);
}
});
यह बहुत सरल और अनुकूलन योग्य है और छोटी परियोजनाओं के लिए बहुत अच्छा काम करने के रूप में कई सत्यापन नियम जोड़ सकते हैं। लेकिन अगर हम एक परियोजना बड़े होते हैं और बहुत अलग फॉर्म होते हैं, तो प्रत्येक बार लिखने के लिए हैंडलर के साथ ऐप घटक सबसे अच्छा विकल्प नहीं है
स्रोत
2015-10-01 11:51:36