首页 > 解决方案 > 我正在构建一个动态生成选项卡的组件,无法弄清楚如何传入标题以动态命名这些选项卡

问题描述

我有一个正在构建的菜单/导航栏组件,它为传​​递给它的每个子组件动态生成选项卡。

一切正常,我现在遇到的唯一问题是我无法弄清楚如何传入标题来命名选项卡。

现在我只是一般地渲染Tab 1, Tab 2, etc.,但我想为每个子组件传递一个标题,并让选项卡显示该值,而不是像这样:

<Tabs>
  <div title={"Overview"}>
    <h1>This is the Overview tab</h1>
  </div>
  <div title={"About"}>
    <h1>This is the About tab</h1>
  </div>
</Tabs>

这是我当前的选项卡组件:

import React, { useState, useMemo } from 'react';
import styled from 'styled-components';

type Props = {
  children: React.ReactNode;
};

const Tabs = (props: Props) => {
  const { children } = props;
  const [tab, setTab] = useState(0);
  const childrenList = React.Children.toArray(children);

  const generateTabs = (amount: number) => {
    let list = [];

    // This is where I generate the tabs and name them
    for (let i = 0; i < amount; i++) {
      list.push(<StyledTabs onClick={() => setTab(i)}>Tab {i + 1}</StyledTabs>);
    }
    return list;
  };

  const current = useMemo(() => childrenList[tab], [tab]);
  const tabs = generateTabs(childrenList.length);

  return (
    <div>
      <div>{tabs}</div>
      <div>{current}</div>
    </div>
  );
};

export default Tabs;

const StyledTabs = styled.button`
  border: none;
  display: inline-block;
`;

这就是它被使用的地方:

...
return (
        <Tabs>
          <div>
            <h1>THIS IS TAB 1</h1>
          </div>
          <div>
           <h1>AND HERE'S TAB 2</h1>
          </div>
        </Tabs>
)

标签: javascriptreactjstypescript

解决方案


您可以使用以下方法获取孩子的标题:child.props.title在 React 中获取子属性

  const tabs = childrenList.map((child,idx)=>{
    const title = (child as any).props.title ?? idx;
    return ( <StyledTabs key={title}  onClick={() => setTab(idx)}>{title}</StyledTabs>);
  })

这是代码的工作沙箱。

https://codesandbox.io/s/read-child-props-n5f8y?file=/src/Tabs.tsx

作为说明,我摆脱了 useMemo 因为它似乎没有做太多并且可能导致显示当前的陈旧值,因为您没有childrenList在依赖数组中使用(这会导致它重新运行每次渲染)。

我还在您的选项卡中添加了一个键,以防止反应抱怨。

我还继续将您的 generateTabs 函数转换为单个映射,因为它比使用 for 循环和数组推送更清晰一些。


推荐阅读