【问题标题】:Validation of multiple reactjs components多个 reactjs 组件的验证
【发布时间】:2016-12-07 06:23:22
【问题描述】:

我在一个表单中有多个组件像这样:

<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 是个坏主意)

【问题讨论】:

    标签: javascript validation reactjs components


    【解决方案1】:

    你可以用状态来做

    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>
         );
       } 
    }
    

    只是在这个组件的宿主容器中通过 state 播放值,PS: rerender 只通过 setState() 发生

    【讨论】:

    • 所以你说值应该作为prop传递给父级。仍然有多个组件需要验证。 &lt;Form_element/&gt;&lt;Form_element/&gt;&lt;Form_element/&gt;&lt;Form_element/&gt; 每个都有不同的有效状态
    • 你在父容器上维护一个状态.. like this.state = {model:[]};然后每次你决定检查只是验证并通过 setState 将状态设置为有效或无效
    • 你的想法很棒。将状态数组的一部分分配给 false 或 true 并在父级中保持状态是个好主意。谢谢。
    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多