当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - this.props.children doesn't contain child methods

问题描述:

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;

Above is the 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;

this is a field and contains validate method. but this method is not accessible from Form.jsx this.props.children.

Another parent Contains

<Form ref={(form)=> {this.form = form;}} className="label-input-group">

<TextField label="Vehicle Owner" required={true} name="owner"/>

</Form>

validate function is undefined and throwing error. this.props.children not updated in the parent after children mount i think. Any way to make it work?

网友答案:

I'm not sure it's a good idea, but you can do something like that :

// 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();
  });
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: