gpt4 book ai didi

javascript - 如何在单击时显示/隐藏具有特定类的元素?

转载 作者:行者123 更新时间:2023-12-02 20:54:33 25 4
gpt4 key购买 nike

我对 React 和 ES6 相当陌生,我正在尝试开发功能,以便当单击按钮 (.featureBtn) 时,会隐藏许多具有特定类的元素(所有 .featureBtn 元素) ,并且另一个组件(附件)变得可见。

可以使用状态和三元语句来完成此操作吗?如果可以,将如何完成?

请参阅下面我的代码。

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;

最佳答案

因为它是React,所以你不需要像vanila js那样使用class。您有权访问状态,因此可以根据您当前的状态调用它。

if(this.state.showFirst) {
this.showFirst();
} else {
this.showSecond();
}

因此这个 showFirst 和 showSecond 可以返回适当的元素。

关于javascript - 如何在单击时显示/隐藏具有特定类的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61523208/

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