如何在反应中访问子状态?

Vla*_*žić 8 javascript reactjs

我用render()方法制作了自己的表单组件,如下所示:

 render() {
    return (
        <form onSubmit={this.onSubmit} ref={(c)=>this._form=c}>
            {this.props.children}
        </form>
    )
}
Run Code Online (Sandbox Code Playgroud)

请注意,子项在此处呈现为{this.props.children},因此用户可以像这样使用此组件:

 <Form onSubmit={this.submit}   >
            <Input  name={"name"} id="name"  labelName="Ime" placeholder="Unesite ime" type="text" >
                 <Validation rule="required" message="Ovo je obavezno polje"/>
            </Input>
            <Input  name={"email"} id="email"  labelName="Email" placeholder="Unesite email adresu" type="text" >
                <Validation rule="required" message="Ovo je obavezno polje"/>
                <Validation rule="email" message="Ovo je nije valjana email adresa"/>
            </Input>
            <button type="submit" value="Pošalji" >Pošalji</button>
       </Form>
Run Code Online (Sandbox Code Playgroud)

我想检查每个Input组件的状态(以获得其有效性)onSubmitMethod().

  checkValidity() {
    var sefl = this;
    this.props.children.map((child) => {
        if (child.type.name === "Input") {

//How to get state of child here
        }
    });
}
onSubmit(event) {
    event.preventDefault();
    var obj = serialize(this._form, { hash: true });
    const validityOfForm = true; //hardcoded for now
    this.checkValidity();
    this.props.onSubmit(obj, validityOfForm);

}
Run Code Online (Sandbox Code Playgroud)

Bal*_*ngh 4

我在一个项目中做了类似的事情,通过将父级的状态作为子级的道具传递,以访问表单元素的父级组件中的子组件数据。

在您的情况下,如果您将组件的状态作为 prop 发送到其子组件中,并且每个子组件都使用父组件的状态,例如 this.props.state.variablename 而不是 this.state.variablename。您将可以控制子组件的状态/数据。

使用 this.prop.children 作为 prop 从表单组件向 childs 发送状态并不简单。下面的链接有助于做到这一点。

/sf/answers/2266012871/

例子:

父组件:

<FormFields
    state={this.state}
    _onChange={this._onChange}
/>
Run Code Online (Sandbox Code Playgroud)

子组件

<Input
    name="fieldname"
    value={this.props.state.fieldname}
    type="text"
    label="Lable text"
    validationMessage={this.props.state.validationMessages.fieldname} 
    onChange={this.props._onChange}
/>
Run Code Online (Sandbox Code Playgroud)

如果您需要更多信息,请与我们联系。