Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

reactjs - React: how to notify parent for changes

I'm trying to wrap bootstrap into components with integrated form validation.

short: Let's say I have

<Form>
  <FieldGroup>
     <Field rules={'required'}/>
  </FieldGroup>
</Form>

Once Field pases validation, how can I notify FieldGroup (parent node) to add a class?

I created a simplified codepen version here

I would like depending on validation status, then change the state of FieldGroup So I can properly change the class name. (add has-warning has-danger etc) and ultimately add class to the Form component.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to pass a callback to the child component. I just forked your codepen and added some snippet as below.

http://codepen.io/andretw/pen/xRENee

Here is the main concept, Make a callback function in "parent" component and pass it to the "child" component

i.e. The child component needs an extra prop to get the callback:

<Form>
  <FieldGroup>
     <Field rules={'required'} cb={yourCallbackFunc}/>
  </FieldGroup>
</Form>

In <FieldGroup /> (parent):

class FieldGroup extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      color: 'blue'
    }
  }

  cb (msg) {
    console.log('doing things here', msg)
  }

  render() { 
    const childrenWithProps = React.Children.map(this.props.children,
     child => React.cloneElement(child, {
       cb: this.cb
     })
    )
    return (
      <div class='fields-group'>
        <label> field </label>
        { childrenWithProps }
      </div>
    );
  }
};

In <Field /> (child):

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

  validate(e){
    let val = e.target.value;
    console.log(!val);
    this.setState({empty: !val});
    //here to notify parent to add a color style!

    // do call back here or you may no need to return.
    this.props.cb(val)

    return !val;
  }

  render() {
    return (
      <div>
        <input type='text' onBlur ={(event) => this.validate(event)}/>
        {this.state.empty && 'empty'}
      </div>
    );
  }
};

And you can do the things you want in the callback function. (You can also pass a callback from <Form /> to the grandson and get it work, but you need to rethink the design of it is good or not.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...