javascript - 如何根据组件id切换状态
问题描述
我正在尝试将两个组件导入应用程序并根据选项卡的单击显示内容+相应地更改标题和描述。到目前为止,我已经得到了这个,但我一直在试图弄清楚如何使它工作。我错过了什么?我对 React 还很陌生,也许有更好的方法来做到这一点。
import React, { Component } from "react";
import Component1 from "./component1";
import Component2 from "./component2";
class App extends Component {
constructor(props) {
super(props);
// this.toggle = this.toggle.bind(this);
this.state = {
tabs: [{
id: '1',
component: <Component1/> ,
title: 'Component1',
description: 'This is it'
}, {
id: '2',
component: <Component2/>,
title: 'Component2',
description: 'This is another one'
}],
activeId: '1'
};
this.switchState = this.switchState.bind(this);
}
switchState(activeId) {
this.setState({ activeId });
}
render() {
return (
<div className={styles.col}>
<div className={styles.card}>
<div className={styles.cardBody}>
<div className={styles.row}>
<div className={styles.col12}>
<div
className={`${
styles.positionRelative
} ${styles.formGroup}`}>
<div
style={{
fontWeight:
"bolder",
color: "#7192a6",
}}>
<span
className={
this.state
.activeId === '1'
? `${
styles.switchState
}`
: `${
styles.switchState
} ${
styles.unselected
}`
}
onClick={() => {
this.switchState();
}}>
Component1{" "}
</span>
/
<span
className={
this.state
.activeId === '2'
? `${
styles.switchState
} ${
styles.unselected
}`
: `${
styles.switchState
}`
}
onClick={() => {
this.switchState();
}}>
{" "}
Component2
</span>
</div>
</div>
</div>
</div>
<div className={styles.row}>
<div className={styles.col12}>
<Component1
/>
<Component2
/>
</div>
</div>
</div>
</div>
</div>
{/* Caption begins */}
<span className={styles.priceCalculatorSeparator} />
<div className={styles.priceCalculatorComment}>
<h1 className={styles.title}>{tabs.title}</h1>
<hr className={styles.hr} align="left" />
<div className={styles.par}>
{tabs.description}
</div>
</div>
</div>
);
}
}
export default App;
解决方案
推荐阅读
- html - “data-bs-dismiss”在 Bootstrap 5 中不起作用
- javascript - 如何在 HTML Photoshop API 颜色代码中使用 5 位 RGB 值
- jasper-reports - Jasper 报告:collection bean 的第一个元素被跳过
- node.js - 为什么我无法获得发送给用户的电子邮件中的任何内容?
- react-native - 键盘出现时防止 webview 内容滚动
- vb.net - 解耦:无法实现间接引用
- plotly - 巧妙地显示地毯文字未显示
- docker - 拉取时 Docker 未经授权
- typescript - 嵌套的 keyof 推理
- entity-framework - 建立 IQueryable,包括基于条件的附加表