首页 > 解决方案 > 在我的 React.js 项目中,我使用 JS 文件中的一些代码在我的网页上添加滑块 TypeError: Cannot read property 'style' of undefined

问题描述

我实际上正面临这个问题,我不明白实际的错误是我在哪里以及缺少哪些术语。

我试图修复它,在 chrome 浏览器的控制台中,它在我在代码段中给出的开始标记行中找到了一个错误。

幻灯片[当前].style.display = 'block'; 这是我在浏览器中发现错误的实际行

export default function Slider() {

  let slide = document.querySelectorAll('.slide');
  var current = 0;

  function cls(){
      for(let i = 0; i < slide.length; i++){
            slide[i].style.display = 'none';
      }
  }

  function next(){
      cls();
      if(current === slide.length-1) current = -1;
      current++;

      **slide[current].style.display = 'block';**
      slide[current].style.opacity = 0.4;

      var x = 0.4;
      var intX = setInterval(function(){
          x+=0.1;
          slide[current].style.opacity = x;
          if(x >= 1) {
              clearInterval(intX);
              x = 0.4;
          }
      }, 100);

  }

  function prev(){
      cls();
      if(current === 0) current = slide.length;
      current--;

      slide[current].style.display = 'block';
      slide[current].style.opacity = 0.4;

      var x = 0.4;
      var intX = setInterval(function(){
          x+=0.1;
          slide[current].style.opacity = x;
          if(x >= 1) {
              clearInterval(intX);
              x = 0.4;
          }
      }, 100);

  }

  function start(){
      cls();
      slide[current].style.display = 'block';
  }
  start();

  return (
   
   
   
   
   <div>

              <div class="container">
                <div class="arrow l" onclick="prev()">
                  <img src={s1.jpg} alt="l" />
                </div>
                <div class="slide slide-1">
                  <div class="caption">
                    <h3>New York</h3>
                    <p>We love the Big Apple!</p>
                  </div>
                </div>
                <div class="slide slide-2">
                  <div class="caption">
                    <h3>Los Angeles</h3>
                    <p>LA is always so much fun!</p>
                  </div>
                </div>
                <div class="slide slide-3">
                  <div class="caption">
                    <h3>Bahar Dar</h3>
                    <p>Thank you, Bahar Dar!</p>
                  </div>
                </div>
                <div class="arrow r" onclick="next()">
                  <img src={s2.jpg} alt="r" />
                </div>
              </div>

    </div>
  )

}

标签: javascriptreactjs

解决方案


推荐阅读