gpt4 book ai didi

reactjs - React ant design Tab图标改变不同状态

转载 作者:行者123 更新时间:2023-12-04 15:16:29 25 4
gpt4 key购买 nike

我正在使用带有 ant design tab 的 React typescript 项目,每次,当我单击第二个选项卡时,第一个选项卡上的图标应更改为锁定,第二个选项卡将具有书本图标。如果我再次单击第一个选项卡,它将显示书本图标,而第二个选项卡变为锁定状态。

stazkblitz here

代码在这里

import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Tabs } from 'antd';
import { FileDoneOutlined, LockOutlined } from '@ant-design/icons';

const { TabPane } = Tabs;

ReactDOM.render(
<Tabs defaultActiveKey="2">
<TabPane
tab={
<span>
<FileDoneOutlined />
Tab 1
</span>
}
key="1"
>
Tab 1
</TabPane>
<TabPane
tab={
<span>
< LockOutlined/>
Tab 2
</span>
}
key="2"
>
Tab 2
</TabPane>
</Tabs>,
document.getElementById('container'),
);

最佳答案

最简单的方法是切换到使用选项卡作为受控组件,这样您就可以根据当前事件的选项卡对渲染进行更改。

然后只需使用三元运算符根据每个选项卡是否处于事件状态来切换图标

工作 Stackblitz:https://stackblitz.com/edit/react-uwhrx3-oajdjw?file=index.js

代码如下:

function TabPage() {
// useState to make the Tabs controlled
const [tab, setTab] = useState("2");
return (
<Tabs
activeKey={tab}
onChange={key => {
setTab(key);
}}
>
<TabPane
tab={
<span>
{/* Use a ternary operator to conditionally render the Icons */}
{tab === "1" ? <FileDoneOutlined /> : <LockOutlined />}
Tab 1
</span>
}
key="1"
>
Tab 1
</TabPane>
<TabPane
tab={
<span>
{tab === "2" ? <FileDoneOutlined /> : <LockOutlined />}
Tab 2
</span>
}
key="2"
>
Tab 2
</TabPane>
</Tabs>
);
}

只是为了好玩,我设置它以便选项卡使用配置数组来设置 Pane 。

https://stackblitz.com/edit/react-uwhrx3-vnkdcq?file=index.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Tabs } from "antd";
import {
FileDoneOutlined,
LockOutlined,
RadarChartOutlined
} from "@ant-design/icons";

const { TabPane } = Tabs;

function TabPage() {
// useState to make the Tabs controlled
const [tab, setTab] = useState("1");

/**
* @type {{title: React.ReactNode; content: React.ReactNode, icon?: Icon}[]}
*
* This config array will generate the tabs with the title and content desired
*/
const tabs = [
{ title: "Tab 1", content: "Tab 1" },
{
title: "Radar Chart",
content: "This is the best chart you'll see",
icon: <RadarChartOutlined />
},
{ title: "Tab 3", content: "Tab 3" }
];
return (
<Tabs
activeKey={tab}
onChange={key => {
setTab(key);
}}
>
{tabs.map(({ title, content, icon }, index) => {
const key = `${index}`;
return (
<TabPane
key={key}
tab={
<span>
{tab === key ? icon ?? <FileDoneOutlined /> : <LockOutlined />}
{title}
</span>
}
>
{content}
</TabPane>
);
})}
</Tabs>
);
}

ReactDOM.render(<TabPage />, document.getElementById("container"));

关于reactjs - React ant design Tab图标改变不同状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64241244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com