如何使用React / Redux找到所有嵌套的组件?

时间:2016-05-27 21:43:27

标签: reactjs react-redux

我希望使用Redux验证表单。我正在尝试使用make一个表单组件,它将遍历子项并查找各种输入组件(不要与本机<input>混淆。

我知道有很多开源解决方案,但我想先了解一些机制,然后再选择任何一种。我有一个Form组件设置来测试这样:

import React from 'react';

export default class Component extends React.Component {
  componentDidMount() {
    this._iterate(this.props.children);
  }

  render(){
    return (
      <form {...this.props}>{this.props.children}</form>
    );
  }

  _iterate(children) {
    React.Children.forEach(children, child => {
      console.log(child);
      if (child.props.children) {
        console.log('get children');
        this._iterate(child.props.children);
      }
    });
  }
};

然后我有另一个带有这样的渲染的组件:

render() {
  return (
    <div>
      <Form>
        <ComponentA />
        <ComponentB />
      </Form>
    </div>
  );
}

现在ComponentAComponentB可能有一个组件可以嵌套更多组件。在这些组件中将是我为Text,Select等制作的React组件

上面的代码只是console.log这个特定渲染中的组件及其中的任何子组件。它不会跳入ComponentA个孩子。

有解决方法吗?

1 个答案:

答案 0 :(得分:1)

这不是您真正想要解决的问题。

反应的力量主要围绕它所鼓励的设计模式,你正在做的是打破这种模式;组件应该只与他们的直系孩子交谈,并回应他们的直系亲属。如果你需要更深入,那么中间的组件需要负责传递数据。

这些组件本身应该拥有您需要的辅助功​​能道具,而不是试图深入了解ComponentA和ComponentB的内部结构。即,<ComponentA onChange={whatever} errorMessage={whatever}/>等然后将这些道具挂钩到他们的孩子应该发生在ComponentA中。