【问题标题】:React: how to notify parent for changesReact:如何通知父母进行更改
【发布时间】:2017-03-31 08:34:37
【问题描述】:

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

短: 假设我有

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

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

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

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

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您需要将callback 传递给子组件。我刚刚 fork 你的 codepen 并添加了一些 sn-p 如下。

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

    这里是主要概念, 在 “父” 组件中制作回调函数并将其传递给 “子” " 组件

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

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

    在&lt;FieldGroup /&gt;(父母):

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

    在&lt;Field /&gt;(孩子):

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

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

    【讨论】:

    • 使用 cloneElement 会减慢应用程序的速度吗?现在每个渲染都必须映射和合并 cb,
    • 那部分是给this.props.children中的每个child添加一个prop,你也可以查看this answer下面的cmets。我没有为此做基准测试,但如果组件中只有几个 this.props.children 应该没问题。
    猜你喜欢
    • 2016-04-25
    • 2017-07-25
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多