简体   繁体   English

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

[英]How to access child state in react?

I have made my own form component with render() method looks like this: 我用render()方法制作了自己的表单组件,如下所示:

 render() {
    return (
        <form onSubmit={this.onSubmit} ref={(c)=>this._form=c}>
            {this.props.children}
        </form>
    )
}

Notice that children are rendered here as {this.props.children} , so the user can use this component like this: 请注意,子项在此处呈现为{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>

I would like to check the state of each Input component (to get its validity) inside onSubmitMethod() . 我想在onSubmitMethod()检查每个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);

}

I have done similar thing in a project by passing state of parent as a prop in child to access child component data in parent component for form elements. 我在项目中做了类似的事情,通过传递父项的状态作为子项中的prop来访问表单元素的父组件中的子组件数据。

In your case if you send component's state in its child as a prop and each child use state of parent like this.props.state.variablename and not this.state.variablename. 在您的情况下,如果您将子组件中的组件状态作为prop发送,并且每个子组件使用像this.props.state.variablename而不是this.state.variablename这样的父级状态。 You will have control on child components' states / data. 您可以控制子组件的状态/数据。

Sending state to childrens from form component using this.prop.children as a prop is not straight forward. 使用this.prop.children作为道具从表单组件向子层发送状态并不是直截了当的。 Below link helps in doing this. 以下链接有助于这样做。

https://stackoverflow.com/a/32371612/1708333 https://stackoverflow.com/a/32371612/1708333

Example: 例:

Parent component: 父组件:

<FormFields
    state={this.state}
    _onChange={this._onChange}
/>

Child component 儿童组件

<Input
    name="fieldname"
    value={this.props.state.fieldname}
    type="text"
    label="Lable text"
    validationMessage={this.props.state.validationMessages.fieldname} 
    onChange={this.props._onChange}
/>

Let me know if you need more information. 如果您需要更多信息,请与我们联系。

Put a ref , say myinput , to the child and get its state by this.refs.myinput.state to access the child's state if you have to. 将一个ref ,比如myinput ,放到孩子myinput ,并通过this.refs.myinput.state获取状态, this.refs.myinput.state在必要时访问孩子的状态。

However, take a look at this thread before you put the ref . 但是,在放入ref之前先看一下这个帖子 There is a better pattern. 有一个更好的模式。

Input should have ref defined. 输入应该有ref定义。 That is easy. 这很容易。 But because Inputs are defined inside Form's parent component (altought rendered inside Form component (because of {this.props.children} ) I should access Form component's parent using child_owner._instance . Relevant part of code is now: 但是因为输入是在Form的父组件中定义的(在Form组件中呈现的(因为{this.props.children} ),我应该使用child_owner._instance访问Form组件的父组件。相关的代码部分现在是:

   checkValidity() {
    var sefl = this;
    var errorsCount = 0;
    this.props.children.map((child) => {

        if (child.type.name === "Input") {
            var refs = child._owner._instance.refs;
            var rules = refs[child.ref].state.validationRules;
            var hiddenRules = refs[child.ref].state.validationRulesHidden;
            if (_.filter(_.values(rules), (elem) => elem == true).length > 0 || _.filter(_.values(hiddenRules), (elem) => elem == true).length>0) {
                errorsCount++;
            }
      }

    });
    if (errorsCount == 0) {
        return true;
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM