如何在React中递归分析和修改组件的后代?

时间:2018-03-08 22:45:18

标签: reactjs

我正在编写表单包装器,我希望它动态更新后代以添加错误消息并为具有验证错误的表单元素添加错误样式。

我知道我可以使用React.Children.map来迭代子项,但我需要递归迭代所有后代,搜索<input><button>元素。

有关如何做到这一点的任何想法?

示例:

const FormWrapper = (props) => {
  let children = this.props.children;

  if (this.prop.disabled) {
    // Note:  do something here with children to recursively
    // look for form elements, update their props.
  }

  return (
    <form>
      {children}
    </form>
  );
}

用法:

<FormWrapper errors={this.errors}>
  <div className="row">
    <div className="col">
      <label>Email:</label>
      <input type="text" name="email">
    </div>
  </div>

  <div className="row">
    <div className="col">
      <label>Password</label>
      <input type="password" name="password">
    </div>
  </div>
</FormWrapper>

2 个答案:

答案 0 :(得分:0)

没有干净,优化和可行的方法来递减儿童图表。你会发现黑客(比如在孩子身上手动调用render),但没有任何干净。

答案 1 :(得分:0)

感谢大家的想法,但实际的解决方案是使用React上下文将错误消息推送到子组件。像魅力一样。

https://reactjs.org/docs/context.html