我在表单中有多个组件,如下所示:
<Form_element check_empty={true} required={true} rows="1" label="Question"</Form_element>
Form_element的定义是:
var Form_element = React.createClass({
getInitialState: function () {
return({valid:false});
)},
render:function()
{
return(<input required="" type={this.props.type}/>)
}
})
如何在提交表单时检查多个Form_element是否无效。(在每个组件上使用refs是一个坏主意)
答案 0 :(得分:0)
你可以用状态
来做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>
);
}
}
只需在此组件的主机容器中通过状态播放值,PS:仅通过setState()
进行重新渲染