[英]How do I toggle div class depending on which button has been clicked in React?
我正在我的 React (ES6) 应用程序中创建一个产品页面来显示不同的产品功能。 每个功能都有一个按钮,每个功能都有一个显示信息的 div。
单击按钮时,它应该将活动的 class 切换到相关的内容 div,但是我对 React 还很陌生,所以我不确定如何切换 class。
我的代码如下:
import React, { useContext } from "react";
import { Link } from "react-router-dom";
import '../App.scss';
import ProductData from "./data/ProductData";
import { ChoicesContext } from "../context/ChoicesProvider";
class Product extends React.Component {
constructor(props) {
super(props);
this.toggleClass= this.toggleClass.bind(this);
this.state = {
active: false,
};
}
toggleClass() {
const currentState = this.state.active;
this.setState({ active: !currentState });
};
static contextType = ChoicesContext;
render() {
const { choices } = this.context;
const CurrentProduct = ProductData.filter(x => x.name === choices.productSelected);
return (
<>
<div className="product wrapper d-md-flex">
<main>
<Link
{/* Need this to toggle active class to <Overlay text={'Overlay 1'} /> */}
className="btn-reverse overlay"
>TOC</Link>
<Link
{/* Need this to toggle active class to <Overlay text={'Overlay 2'} /> */}
className="btn-reverse overlay"
>Puresure</Link>
<Overlay text={'Overlay 1'} />
<Overlay text={'Overlay 2'} />
</main>
</div>
</>
)
}
}
export default Product;
class Overlay extends React.Component {
render() {
return (
<div className="overlay">
<h2>{this.props.text}</h2>
</div>
)
}
}
我建议你使用 npm package classNames
import classNames from 'classnames';
...
const classes = classNames('btn-reverse', 'overlay', {
'active': this.state.active
})
...
<div className={classes}> .... </div>
它适用于下一个场景:如果 this.state.active === true,则类将是“btn-reverse overlay active”否则为“btn-reverse overlay”
另外,我可以建议您不要在渲染中过滤您的产品,尽量避免它。 因为无论你的组件为什么会重新渲染,你总是过滤产品
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.