繁体   English   中英

如何在点击时显示/隐藏具有特定 class 的元素?

[英]How can I show/hide elements with a specific class on click?

我对 React 和 ES6 还很陌生,我正在尝试开发功能,以便在单击按钮 (.featureBtn) 时,会隐藏许多具有特定 class (all.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;

因为它是反应,所以你不需要像 vanila vanila js那样处理class 您可以访问 state,因此可以根据您当前的 state 调用它。

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

所以这个showFirst and showSecond可以返回适当的元素。

我会通过添加一个 state 变量来解决这个问题。让我们称之为显示。 您可以更新显示以在单击按钮时隐藏。 使用此变量有条件地更改要隐藏的按钮的类名。

您可以使用类名 npm package。 用于将条件类名添加到要隐藏的按钮。

并对附件使用三元运算符。 同样的 state 变量可用于显示或隐藏附件。

{ !this.state.show && <Accessories/>}

使用三元运算符和一个 state 变量,onClick 更改 state 值。

{this.state.stateVariable? <>组件:空}

您可以编写一个 function,首先获取要通过 class 名称删除的元素,获取按钮,然后切换显示 onClick。

查看代码

 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() ) } //function to hide elements with classname.featureBtn. toggleDisplay(){ const elementsToBeRemoved= document.getElementsByClassName('featureBtn'); const button = document.getElementsByTagName('button'); //if it is a specific button, give the button an ID and use getElementById if(elementsToBeRemoved){ elementsToBeRemoved.styles.display('none') //insert the other component to be shown } else{ elementsToBeRemoved.styles.display('inline') //hide the other component } //attach this function on the onClick property and see what happens. } 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM