【问题标题】:Iterate over an Array of Symbols遍历符号数组
【发布时间】:2020-11-26 12:04:10
【问题描述】:

我想问一下,是否有可能以某种方式迭代符号数组。 我有这个代码:

import React, { FunctionComponent, useState } from "react";

import { bemClassNames } from "@multiweb/reactUtils";

export type TabsProps = {
  children: any;
}

export const Tabs: FunctionComponent<TabsProps> = ({
  children
}) => {
  const classNames = bemClassNames("tabs-component");

  const tabs = children;

  const [activeTabIndex, setActiveTabIndex] = useState(0);

  const handleTabClick = (tabIndex: number) => {
    setActiveTabIndex(tabIndex === activeTabIndex ? activeTabIndex : tabIndex);
  }

  return (
    <div className={classNames()} role="tabpanel">
      <ul className={classNames("tabs-nav")}>
        {tabs.map((child: any, index: number) => {
          return React.cloneElement(child, {
            tabIndex: index,
            onClick: handleTabClick,
            isActive: index === activeTabIndex
          });
        })}
      </ul>
    </div>
  );
}

我收到此错误:TypeError: tabs.map is not a function。

所以我建议,我需要一些方法来迭代符号数组或将符号转换为字符串。 有人知道吗,怎么做?

非常感谢。

【问题讨论】:

  • 可能是因为选项卡没有存储为数组。检查标签的类型
  • React.Children(tabs).map

标签: javascript arrays reactjs typescript symbols


【解决方案1】:

请使用 React.Children.map 进行迭代 见例子:

        <div>
        {React.Children.map(children, (child, i) => {          
          return child
        })}
      </div>

附:没有对符号数组进行迭代的特殊方法。您可以只使用 map、reduce、forEach ...

【讨论】:

  • 谢谢。这绝对是正确的一种解决方案。但是现在,tabIndex、onClick、isActive 属性没有传递给较低的组件。在较低的组件中,当我执行 console.log(tabIndex) 时,它返回“未定义”。
  • 对不起,这只是一个例子。您仍然应该使用 React.cloneElement 并传递道具,就像您在示例中所做的那样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2016-01-31
相关资源
最近更新 更多