this.props.children不包含子方法

时间:2017-02-02 04:35:49

标签: javascript reactjs

import React from 'react';
import {render} from 'react-dom';

class Form extends React.Component {
    constructor(props) {
        super(props);
        this.validate = this.validate.bind(this);
    }

    componentDidMount() {

    }

    validate() {
        this.props.children.map((field)=> {
            field.validate();
        });
    }

    render() {
        return (
            <form className={this.props.className}>
                {this.props.children}
            </form>
        );
    }
}

export default Form;

以上是Form.jsx

import React from 'react';
import '../form.css';

class TextField extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            valid: true
        };
        this.validate = this.validate.bind(this);
    }

    validate() {
        if (!!this.props.required) {
            if (this.refs.field.value.trim().length === 0) {
                this.setState({
                    valid: false
                });
                return false;
            } else {
                this.setState({
                    valid: true
                });
                return true;
            }
        }
        return true;
    }

    setValue(event) {
        if (this.validate()) {
            this.props.setValue(this.props.name, event.target.value);
        }
    }

    render() {
        var input = (
            <span className={this.state.valid ? null : 'field-invalid'}>
                    <input ref="field" type="text" name={this.props.name} placeholder={this.props.placeholder}
                           onBlur={this.setValue.bind(this)}/>
            </span>
        );
        var field = input;
        if (this.props.label) {
            field = (
                <div className="row">
                    <label className={"col-3 align-r" + (!!this.props.required ? " field-required" : "")}>
                        {this.props.label}
                    </label>
                        <span className="col-6">
                            {input}
                        </span>
                </div>
            );
        }

        return field;
    }
}

export default TextField;

这是一个字段,包含验证方法。但无法从Form.jsx this.props.children访问此方法。

另一位父母包含

<Form ref={(form)=> {this.form = form;}} className="label-input-group">
     <TextField label="Vehicle Owner" required={true} name="owner"/>
</Form>

验证函数未定义并抛出错误。 this.sprops.children在孩子登上之后没有在父级中更新我认为。有什么方法可以使它发挥作用吗?

1 个答案:

答案 0 :(得分:1)

我不确定这是个好主意,但你可以这样做:

// Form
constructor(props) {
  super(props);
  this.validate = this.validate.bind(this);
  this.childrenInstances = [];
  this.props.children.forEach(field => {
    field.ref = inst => this.childrenInstances.push(inst);
  });
}

validate() {
  this.childrenInstances.forEach(field => {
    field.validate();
  });
}