反应;根据我所在的选项卡从数组中渲染组件
React; rendering components from an array depending on what tab im in
我希望我的代码做什么
我需要根据状态制作显示不同组件的选项卡
我的问题
我不知道如何使用条件渲染正确的组件,具体取决于我在 React 中的哪个选项卡
到目前为止我的代码在做什么
- 我在 const allTabs 中有一个包含所有组件的数组
- 根据我单击的按钮,tabNum 的状态会发生变化
import React, {useState} from "react";
import Tabcomp1 from './../components/tabcomp1';
import Tabcomp2 from './../components/tabcomp2';
const allTabs = [Tabcomp1, Tabcomp2];
const Pagetwo = () =>{
const[tabNum, setTabNum] = useState("0");
const changeTab = (e) =>{
e.preventDefault();
if (tabNum === "0") {
setTabNum("1");
console.log(tabNum);
}
else {
setTabNum("0");
console.log(tabNum);
}
}
return(
<div>
<h1>you are now on page 2</h1>
{/* tab1 */}
<button id={0} onClick={changeTab}>tab 1</button>
{/* tab2 */}
<button id={1} onclick={changeTab}>tab 2</button>
<br />
{/* display the correct component here */}
</div>
)
}
export default Pagetwo;
在您的按钮事件处理程序中,您可以将索引设置为
onClick={() => setTabNum(0 // tab index here)}
在你的按钮下面你可以渲染它
{allTabs[tabNum]}
我希望我的代码做什么
我需要根据状态制作显示不同组件的选项卡
我的问题
我不知道如何使用条件渲染正确的组件,具体取决于我在 React 中的哪个选项卡
到目前为止我的代码在做什么
- 我在 const allTabs 中有一个包含所有组件的数组
- 根据我单击的按钮,tabNum 的状态会发生变化
import React, {useState} from "react";
import Tabcomp1 from './../components/tabcomp1';
import Tabcomp2 from './../components/tabcomp2';
const allTabs = [Tabcomp1, Tabcomp2];
const Pagetwo = () =>{
const[tabNum, setTabNum] = useState("0");
const changeTab = (e) =>{
e.preventDefault();
if (tabNum === "0") {
setTabNum("1");
console.log(tabNum);
}
else {
setTabNum("0");
console.log(tabNum);
}
}
return(
<div>
<h1>you are now on page 2</h1>
{/* tab1 */}
<button id={0} onClick={changeTab}>tab 1</button>
{/* tab2 */}
<button id={1} onclick={changeTab}>tab 2</button>
<br />
{/* display the correct component here */}
</div>
)
}
export default Pagetwo;
在您的按钮事件处理程序中,您可以将索引设置为
onClick={() => setTabNum(0 // tab index here)}
在你的按钮下面你可以渲染它
{allTabs[tabNum]}