javascript - 我正在构建一个动态生成选项卡的组件,无法弄清楚如何传入标题以动态命名这些选项卡
问题描述
我有一个正在构建的菜单/导航栏组件,它为传递给它的每个子组件动态生成选项卡。
一切正常,我现在遇到的唯一问题是我无法弄清楚如何传入标题来命名选项卡。
现在我只是一般地渲染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>
)
解决方案
您可以使用以下方法获取孩子的标题: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 循环和数组推送更清晰一些。
推荐阅读
- c++ - 迷失在试图理解这个结构编码问题
- jquery - 将表单输入附加到dom后如何专注于表单输入?
- dart - 如何转换地图
到地图 在飞镖? - mongodb - 如何在 mongo 查询中执行嵌套查找?
- python - 将对象正确导入烧瓶?Flask 无法导入姓名邮件
- spring-boot - java.lang.NoSuchMethodError:org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient。
(Ljava/util/function/Consumer;)V - scala - Kafka:是否有用于 scala 的 Kalfa 客户端 API?
- object - 对象的ES6过滤器数组是否存在属性
- arrays - 如何以编程方式列出 Ruby 中 Array 的所有方法?
- c# - Jquery将项目从一个列表框移动到另一个列表框