I have multiple component in a form Like this:
<Form_element check_empty={true} required={true} rows="1" label="Question"</Form_element>
The definition of Form_element is:
var Form_element = React.createClass({
getInitialState: function () {
return({valid:false});
)},
render:function()
{
return(<input required="" type={this.props.type}/>)
}
})
How can I check if multiple Form_element's are invalid when the form is submitted.(Using refs on each component is a bad idea)
you could do it with state
class FormElement extends Component {
constructor(props){
super(props);
}
render(){
const { state,value,type } = this.props;
let errorClass={color:'red'};
let normalClass={color:'black'};
return (
<div>
{ (state == 0)?
<input style={errorClass} type={type}
value={this.props.value}>:
<input style={normalClass} type={type}
value={value}>
}
</div>
);
}
}
class Parent extends Component {
constructor(props){
super(props);
this.onCheck = this.onCheck.bind(this);
this.state = {name:{value:'',status:0 },address:{ value:'',status:0} };
}
onCheck(){
let ok = {};
Object.keys(this.state).forEach(x=>{
let element = this.state[x];
// check if the status is alright
if ( cond satisfy your validation ){
ok[x] = this.state[x];
}
});
// let's say that the checking was done we update the state to rerender
this.setState(Object.assign({},this.state,ok);
}
render(){
return (
<div>
<FormElement valid={this.state.name.status} type={'text'}></FormElement>
<FormElement valid={this.state.address.status} type={'text'}></FormElement>
<button onPress={this.onClick}>submit</button>
</div>
);
}
}
just play the value through state at the hosting container of this component, PS: rerender only happens through setState()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.