javascript - 如何在单击时显示/隐藏具有特定类的元素?
问题描述
我对 React 和 ES6 还很陌生,我正在尝试开发功能,以便在单击按钮 (.featureBtn) 时,隐藏许多具有特定类的元素(所有 .featureBtn 元素),而另一个组件(附件)变得可见。
这可以使用 state 和三元语句来完成吗?如果可以,怎么做?
请在下面查看我的代码。
class ProductView extends React.Component {
static contextType = ChoicesContext;
constructor(props) {
super(props);
this.forwardSequence = this.forwardSequence.bind(this);
this.reverseSequence = this.reverseSequence.bind(this);
}
static sequenceImages(folder, filename, type) {
let images = [];
for (let i = 0; i < 51; i++) {
images.push(<img src={require(`../images/sequences/${folder}/${filename}_000${i}.jpg`)} alt="" className={`${type} sequenceImage`} />);
}
return images;
}
async sleep(ms) {
return new Promise(r => setTimeout(r, ms))
}
async forwardSequence(sequence, effect) {
Array.prototype.reduce.call
( sequence
, (r, img) => r.then(_ => this.sleep(50)).then(_ => effect(img))
, Promise.resolve()
)
}
async reverseSequence(sequence, effect) {
Array.prototype.reduceRight.call
( sequence
, (r, img) => r.then(_ => this.sleep(50)).then(_ => effect(img))
, Promise.resolve()
)
}
render() {
const etseq = document.getElementsByClassName("exploreTech");
const uiseq = document.getElementsByClassName("userInterface");
const { choices } = this.context;
const CurrentProduct = ProductData.filter(x => x.name === choices.productSelected);
return (
<>
<div className="productInteractive wrapper">
{CurrentProduct.map((item, i) => (
<main className={item.slug}>
<div key={i} className="imageSequence">
<img src={require(`../images/sequences/${item.static_img}`)} alt="" className="staticImage" />
{ProductView.sequenceImages(item.explore_tech_img_folder, item.explore_tech_filename, "exploreTech")}
{ProductView.sequenceImages(item.user_interface_img_folder, item.user_interface_filename, "userInterface")}
</div>
{/* When one of the two buttons below are clicked, they should both hide (presumably using the featureBtn class), and the <Accessories /> component should become visible. */}
<button
onClick={() => this.forwardSequence(etseq, img => img.style.opacity = 1)}
className="btn featureBtn userInterfaceBtn"
>User Interface</button>
<button
onClick={() => this.forwardSequence(uiseq, img => img.style.opacity = 1)}
className="btn-reverse featureBtn exploreTechnologiesBtn"
>Explore Technologies</button>
<Accessories />
</main>
))}
</div>
</>
);
}
}
export default ProductView;
解决方案
因为它是反应,你不需要做class
like vanila js
。您可以访问状态,因此可以根据您当前的状态调用它。
if(this.state.showFirst) {
this.showFirst();
} else {
this.showSecond();
}
所以这showFirst and showSecond
可以返回适当的元素。
推荐阅读
- qt - 即使我按下 Key_F10 或 Key_F11 也会实现 Qt::Key_F9 案例
- loops - Fortran:带有实型参数的 do-loop
- sql - SQL Server 临时表检查性能
- c++ - 未调用重写的虚拟方法
- javascript - 检查jquery中的所有输入值
- javascript - 远程视频未显示在一端 - WebRTC 视频聊天应用程序
- mysql - 列出 1960 年代“经典汽车”产品线中所有产品的产品名称
- blazor - 如何将本机事件与剃刀页面中的文档绑定(Blazor 服务器端应用程序不是互操作文件)
- scala - 使用与 100K 演员共享的并发哈希图是否安全?
- html - 页面滚动后标题变宽