【问题标题】:Iterating React component children迭代 React 子组件
【发布时间】:2018-10-23 21:54:50
【问题描述】:

是否有任何入口点可以在子树中找到实际输入 (child.type === 'input')

class MyForm extends React.Component {
  parseChildren(children) {
    React.Children.forEach(children, child => {
      if (child) {
        console.log('type', child.type);
        if (child.props && child.props.children) {
          this.parseChildren.bind(this)(child.props.children);
        }
      }
    });
  }
  componentWillMount() {
    this.parseChildren(this.props.children);
  }
  componentDidMount() {
    this.parseChildren(this.props.children);
  }
  render() {
    return <form>{this.props.children}</form>;
  }
}

class MyInput extends React.Component {
  render() {
    return (
      <p>
        My beautiful input <input {...this.props} />
      </p>
    );
  }
}

ReactDOM.render(
  <MyForm>
    <MyInput type="text" />
  </MyForm>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【问题讨论】:

  • 你想检查一个孩子是否是MyInput类的实例吗?
  • 没有。我想检查在子渲染树的深处是否有输入组件(反应包装器围绕 dom 输入而不是 dom 节点)。

标签: reactjs children


【解决方案1】:

你描述的问题不是很清楚。你想达到什么目标?

在我看来,在MyForm 中传递孩子然后只渲染其中的一部分并不是最好的方法。

为什么不在将组件(输入)数据作为Form's children 传递之前过滤它们,然后只传递与搜索条件匹配的那些?或者,也许我理解错了?

【讨论】:

  • 我的问题与输入字段放入表单后的修饰有关。
猜你喜欢
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 2021-07-03
  • 2016-05-16
  • 2021-06-05
  • 2021-06-17
  • 1970-01-01
相关资源
最近更新 更多