2016-06-09 83 views
0

我正尝试用自定义输入字段构建表单。问题是形式的结构不是预先知道的。我希望它尽可能多地抽象出常用的功能。所以我创建了一个表单组件,它实际上会负责存储所有输入组件的值和提交时的操作。留在表格中,html应该如何被用户写入。将父子元素放在父元素中reactjs

这里是一个快照:

一个自定义输入区:

class InputField extends React.Component { 

    constructor(props, context) { 
     super(props, context); 

     this.state = { 
      id: this.props.id, 
      value: this.props.value || '', 
      valid: this.props.isValidationRequired || this.props.required ? true : false, 
      errorVisible: false, 
      errorMessage: '' 
     }; 
    } 

    //different helper and conchange function 

    render() { 

     let props = this._getInputFieldProps(); 


       return (<div className={this.props.fieldParentClass}> 
        <label for={this.props.id}>{this.props.name}</label> 
        <input {...props}/> 
        <span className={this.state.errorVisible ? 'show' : 'hide'}>{this.state.errorMessage}</span> 
       </div>) 
    } 

} 

export default InputField; 

形式: -

class FormComponent extends React.Component { 
    constructor(props, context) { 
     super(props, context); 

     this.state = { 
      submitButton: { 
       buttonClasses: ['btn-default', 'vy-btn-secondary'], 
       buttonText: "SUBMIT", 
      } 
     }; 
    } 

    //functions for storing values of children and submit 


    render() { 
     return <form role="form" class="vm-form"> 
        <Button disabled={this.state.submitValid} onClick={this._onSubmit.bind(this)} button={this.state.submitButton}></Button> 
       </form> 
    } 
} 

export default FormComponent; 

和来电类: -

class LeadDetails extends React.Component { 

    constructor(HttpService, $state, VymoDataService, props, context) { 
     super(props, context); 
    } 


    render() { 
     return (<FormComponent > 
      <InputField placeholder='hi' value="1" 
      type="text" 
      id="name" 
      maxlength="10"></InputField> 
     </FormComponent>) 
    } 
} 

所以现在我可以包装我的输入字段组件t在一些html包装中,并以我想要的方式自定义外观。但是这里只有表单获取呈现不是输入字段,既不表现为小孩。

我在某种程度上完全错了吗?我应该怎么做?

回答

0

在你FormComponent渲染方法,你需要渲染的“孩子”,这将是位于this.props.children

render() { 
    return <form role="form" class="vm-form"> 
       {this.props.children} 
       <Button disabled={this.state.submitValid} onClick={this._onSubmit.bind(this)} button={this.state.submitButton}></Button> 
      </form> 
} 

这样做的原因是,当你去实际创建(实例)的表单,您正在执行以下操作:

<FormComponent > 
    <InputField placeholder='hi' value="1" 
    type="text" 
    id="name" 
    maxlength="10"></InputField> 
</FormComponent> 

组件标记之间的内容是“子”。在实例化(props.children)期间,子元素被传递给你的组件,它取决于组件渲染这些子元素。你可能期望孩子被自动渲染的原因是因为React对待<ReactComponents><normal-dom-elements>不同。

每当反应看一个<Tag>与一个大写字母开头,它假定它是一个反应成分,基本上把它转换:

<Tag foo="bar"><div>hello</div></Tag> 

到这样的事情:

new Tag({ 
    foo: "bar", 
    children: React.createElement('div', null, "hello") 
})