【问题标题】:Filter out children of a React component过滤掉 React 组件的子组件
【发布时间】:2020-06-11 05:41:10
【问题描述】:

我目前正在通过以下方式映射我的父组件子项的值:

const subRows = React.Children.map(this.props.children, (child, i) => {
  return child;
});

我想要的是针对这些孩子的类型值,这样我就可以在返回中过滤掉特定的孩子。任何人都知道是否有一种简单的方法可以实现这一目标?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您可以通过 props 访问子级的属性。

    如果要过滤children,可以使用React.Children.toArray得到一个普通的JS数组,然后使用它的Array.prototype.filter方法。

    const subRows = React.Children.toArray(this.props.children).filter((child, i) => {
      return child.props.someProp;
    });
    

    请记住:

    React.Children.toArray() 在展平子列表时更改键以保留嵌套数组的语义。也就是说,toArray 为返回数组中的每个键添加前缀,以便每个元素的键的范围都限定为包含它的输入数组。

    您还可以使用React.Children.forEach 并填充外部范围内可用的数组:

    const subRows = [];
    React.Children.forEach(this.props.children, (child, i) => {
      if (child.props.someProp) {
        subRows.push(child)
      }
    });
    

    【讨论】:

      【解决方案2】:
      React.Children.toArray(this.props.children).filter(...)
      

      【讨论】:

      • 虽然code may answer the question,但提供有关为什么和/或如何此代码回答问题的附加上下文可提高其长期价值。
      【解决方案3】:

      我编写了一个库来扩展 React Children 实用程序,其中包含过滤甚至深度过滤反应组件的功能

      https://fernandopasik.com/react-children-utilities/filter

      import React from 'react';
      import { filter } from 'react-children-utilities';
      
      const Filtered = ({ children }) => (
        <div>
          {filter(children, (child) => child.type === 'span')}
        </div>
      );
      
      
      

      【讨论】:

        猜你喜欢
        • 2021-05-22
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-06
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多