reactjs - react : how to notify parent for changes

标签 reactjs

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

简短: 假设我有

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

一旦Field通过验证,如何通知FieldGroup(父节点)添加类?

我创建了一个简化的codepen版本here

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

最佳答案

您需要传递callback到子组件。我刚刚 fork 了你的 codepen 并添加了一些代码片段,如下所示。

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

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

即子组件需要额外的 prop 来获取回调:

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

并且你可以在回调函数中做你想做的事情。 (你也可以将 <Form /> 的回调传递给孙子并使其工作,但你需要重新考虑它的设计是否好。)

关于reactjs - react : how to notify parent for changes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644092/

相关文章:

reactjs - prop 类型验证中出现误报

javascript - 使用 JS linter/formatter 将条件(else/if)运算符转换为逻辑运算符(&& ||)?

javascript - React - 更改单个跨度类的背景不起作用

javascript - 如何从 ReCharts 折线图中删除点?

reactjs - 为 onClick 事件列出的函数在 ReactJS 上加载时触发

css - 如何使用nextjs更改图像大小

javascript - 用户滚动到特定div的底部时,标题应显示

javascript - 让辅助方法在状态初始更新时运行

javascript - 如何在 chartjs 中显示百分比符号?

reactjs - React PDF 查看器组件不断重新渲染