小编典典

React:如何通知父母更改

reactjs

我正在尝试将Bootstrap包装到具有集成表单验证的组件中。

简短:假设我有

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

一旦Fieldpases验证,我怎么能通知FieldGroup(父节点)来添加一个类?

我在这里创建了一个简化的Codepen版本

我想根据验证状态,然后更改FieldGroup的状态,以便可以正确更改类名。(添加has-warning has- danger等),并最终将类添加到Form组件。


阅读 192

收藏
2020-07-22

共1个答案

小编典典

您需要将a传递callback给子组件。我只是分叉了您的Codepen,并添加了以下代码段。

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

这是主要概念, “父” 组件中创建 一个回调函数, 并将其传递给 “子” 组件

即子组件需要一个额外的道具来获取回调:

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

<FieldGroup />(父母):

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>
    );
  }
};

<Field />(孩子):

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>
    );
  }
};

您可以在回调函数中执行所需的操作。(您还可以从回调传递<Form />给孙子并使它工作,但是您需要重新考虑它的设计是好是坏。)

2020-07-22