【问题标题】:ReactJS children - filter out null valuesReactJS 子级 - 过滤掉空值
【发布时间】:2018-09-13 14:05:52
【问题描述】:

我正在渲染我的组件:

<PanelGroup>
    {this.renderPanel1()}
    {this.renderPanel2()}
    {this.renderPanel3()}
</PanelGroup>

现在我的一个面板只有在其可用属性设置为true 时才可用。 render() 方法否则返回 null。

我的&lt;PanelGroup&gt; 应该在除最后一个元素之外的所有元素的底部添加一个分隔线。

我尝试使用下面的代码来完成,但是因为即使panel2 返回 null,仍然添加了分隔符,并且代码不起作用。

如何过滤掉所有返回 null 的面板? :)

<div>
   {React.Children.map(
       React.Children.toArray(props.children),
           (child: React.ReactElement<PanelProps>, i) => {
               return (
                     <div>
                        {React.cloneElement(child as React.ReactElement<PanelProps>, child.props)}
                        {/*Add divider after all elements except last*/}
                        {i < React.Children.count(props.children) -1 && <Divider/>}
                     </div>
                )
           }
        )}
</div>

【问题讨论】:

  • 你在哪里设置可用的prop?也许available 属性的逻辑可以用于过滤...
  • 仍在搜索:D
  • 顺便可以直接将props.children传入React.Children.map,无需调用React.Children.toArray
  • Olivier,然后我得到“Uncaught TypeError: Cannot read property 'props' of null”

标签: reactjs


【解决方案1】:

你必须利用Array.filter()

const MyComponent = ({ children }) => {
  // This filter will return only not null values
  const children = React.Children.toArray(children).filter(Boolean);
  
  // return ...
};

工作示例:

const array = [1,2,3,null,4,null,5,null];
console.log(array.filter(Boolean));

【讨论】:

  • 嘿 Mosè,当我添加过滤器时仍然无法工作。 o => o 够吗?
  • o => o 足以过滤空值,在过滤器之前打印数组并检查它是一个带有空元素的普通数组,因为 o => o 将检查集合中的元素本身是否为空,不是它的属性之一
  • 这是回答问题。他说的是渲染一个实际上不是 null 的组件,它是一个渲染 null 的组件,具有 () =&gt; null 值。所以它被认为是真实的。
【解决方案2】:

children 不是一个数组,不能被这样对待(React.children 除外)。

如果您尝试使用标准数组技术过滤空值,它将不起作用!

我只是为此浪费了一些时间。

我遇到的问题是我将孩子视为一个数组,然后做一些 ramda 拒绝所有的空值,它不会工作。

只要我将React.children.toArray(children) 作为“拒绝空值”过滤器的输入,一切都很好。

假设有 2 个孩子,其中一个为空,由以下内容生成:

<PanelGroup>
    {this.renderPanel1()}
    {false && this.renderPanel2()}
</PanelGroup>

在我的面板组渲染器中:

console.log(children.length) // 2
console.log(R.reject(R.isNil, children).length) // 2
console.log(R.reject(R.isNil, React.Children.toArray(children)).length) // 1

产量:

2
2
1

HTH

【讨论】:

    【解决方案3】:

    代替

    {i < React.Children.count(props.children) -1 && <Divider/>}
    

    我试过了

    {i < React.Children.toArray(props.children).length - 1 && <Divider/>}
    

    那行得通。 toArray 删除空值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多