在reactjs中,javascript clientWidth的最佳替代方案是什么?

在reactjs中,javascript clientWidth的最佳替代方案是什么?,reactjs,Reactjs,我正在尝试将JavaScript代码转换为ReactJS 编译器不显示任何错误,但浏览器在运行时抛出错误 我希望看到它可行,但我得到了一些错误 我的滑块即使在我单击左箭头或右箭头时也不会显示图像,然后当我注释这两行时,浏览器会带我进行调试 const size = carouselImages[0].clientWidth; carouselSlide.style.transform = 'translateX(' + (size * counter) + 'px)' ---------

我正在尝试将JavaScript代码转换为ReactJS

编译器不显示任何错误,但浏览器在运行时抛出错误

我希望看到它可行,但我得到了一些错误

我的滑块即使在我单击左箭头或右箭头时也不会显示图像,然后当我注释这两行时,浏览器会带我进行调试

const size = carouselImages[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (size * counter) + 'px)' 



-----------------------------------Carousel.css--------------------------
    * {
      padding:0px;
      margin:0px;
      box-sizing:border-box;
      }
    
      .carousel-container
      {
        width:60%;
        margin:auto;
        border: 5px solid black;
        overflow:hidden;
        position: relative;
      }
    
      .carousel-slide{
        display: flex;
        width:100%;
        height:500px;
      }
    
      #prevBtn{
      position:absolute;
      top: 50%;
      z-index:10;
      left:5%;
      font-size:30px;
      color:grey;
      opacity: 0.9;
      cursor:pointer;
      }
    
      
      #nextBtn{
        position:absolute;
        top: 50%;
        z-index:10;
        right:5%;
        font-size:30px;
        color:grey;
        opacity: 0.9;
        cursor:pointer;
        }


-----------------------------------Carousel.js--------------------------

import React from "react";
import './Carousel.css'
   
const Carousel = () => {   

  const carouselSlide = document.querySelector('.carousel-slide');
   const carouselImages = document.querySelectorAll('.carousel-slide img');
   let counter = 1;   
   const size = carouselImages[0].clientWidth;
   carouselSlide.style.transform = 'translateX(' + (size * counter) + 'px)'   

   function showNextItemFlex() {   
     debugger;
       if(counter >= carouselImages.length - 1) return;
        carouselSlide.style.transition = "transform 0.4s ease-in-out";
        counter ++;
       // console.log(counter);
       carouselSlide.style.transform = 'translateX('+ (size *  counter) + 'px)';
   }
   
   function showPreviousItemFlex() {
     debugger;
    if(counter <= 0) return;
    carouselSlide.style.transition = "transform 0.4s ease-in-out";
    counter--;
   // console.log(counter);
   carouselSlide.style.transform = 'translateX('+ (size *  counter) + 'px)';    
     
   }

   function fireTransitioned()
   {
      debugger;  
    if(carouselImages[counter].id === 'lastClone')
        {
                    carouselSlide.style.transition = "none";                    
                    counter = carouselImages.length - 2;
                    carouselSlide.style.transform = 'translateX('+ (size *  counter) + 'px)';    
        }
        if(carouselImages[counter].id === 'firstClone')
        {
                    carouselSlide.style.transition = "none";                    
                    counter = carouselImages.length - counter;
                    carouselSlide.style.transform = 'translateX('+ (size *  counter) + 'px)';    
        }


   }
      

  return (
   <div className="carousel-container">
  {/* <i id="prevBtn" onClick={showPreviousItem}>&#10094;</i>
  <i id="nextBtn" onClick={showNextItem}>&#10095;</i> */}
  <i id="prevBtn" onClick={showPreviousItemFlex}>&#10094;</i>
  <i id="nextBtn" onClick={showNextItemFlex}>&#10095;</i>
  <div className="carousel-slide" onTransitionEnd={fireTransitioned}>
    <img id="lastClone" src="https://source.unsplash.com/InR-EhiO_js"  alt="None"/>
    <img  src="https://source.unsplash.com/gKk9rpyDryU" alt="None " />
    <img src="https://source.unsplash.com/VFGEhLznjPU"  alt="None"/>
    <img src="https://source.unsplash.com/InR-EhiO_js"  alt="None"/>
    <img id="firstClone" src="https://source.unsplash.com/gKk9rpyDryU" alt="None " />
  </div> 
</div>
 ); 
  }

  export default Carousel;


Application built with
{
  "react": "16.13.0", 
  "react-dom": "^16.13.0", 
  "react-redux": "^7.2.0",
  "redux": "^4.0.4"
  "@material-ui/core": "^4.9.5"
}
const size=carouselImages[0].clientWidth;
carouselSlide.style.transform='translateX(+(大小*计数器)+'px)'
-----------------------------------Carousel.css--------------------------
* {
填充:0px;
边际:0px;
框大小:边框框;
}
.转盘式集装箱
{
宽度:60%;
保证金:自动;
边框:5px纯黑;
溢出:隐藏;
位置:相对位置;
}
.旋转滑梯{
显示器:flex;
宽度:100%;
高度:500px;
}
#prevBtn{
位置:绝对位置;
最高:50%;
z指数:10;
左:5%;
字体大小:30px;
颜色:灰色;
不透明度:0.9;
光标:指针;
}
#下一个{
位置:绝对位置;
最高:50%;
z指数:10;
右:5%;
字体大小:30px;
颜色:灰色;
不透明度:0.9;
光标:指针;
}
-----------------------------------Carousel.js--------------------------
从“React”导入React;
导入“./Carousel.css”
const Carousel=()=>{
const carouselSlide=document.querySelector(“.carousel slide”);
const carouselImages=document.queryselectoral('.carousel slide img');
设计数器=1;
const size=carouselImages[0]。客户端宽度;
carouselSlide.style.transform='translateX(+(大小*计数器)+'px)'
函数showNextItemFlex(){
调试器;
如果(计数器>=carouselImages.length-1)返回;
carouselSlide.style.transition=“转换0.4s轻松输入输出”;
计数器++;
//控制台日志(计数器);
carouselSlide.style.transform='translateX(+(大小*计数器)+'px');
}
函数showPreviousItemFlex(){
调试器;
如果(计数器9 | const size=carouselImages[0].clientWidth;
10 | carouselSlide.style.transform='translateX(+(大小*计数器)+'px)'
11 |    
12 |///类似于componentDidMount和componentDidUpdate:
视图编译
带挂钩的渲染器
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:14803
14800 |   }
14801 | }
14802 | 
>14803 | var children=Component(props,secondArg);//检查是否有渲染阶段更新
| ^  14804 | 
14805 |如果(workInProgress.expirationTime==renderExpirationTime){
14806 |//只要渲染阶段更新继续,就保持循环渲染
视图编译
MountUndeterminateComponent
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:17482
17479 | 
17480 | SETISRENDING(正确);
17481 | ReactCurrentOwner$1.current=工作进度;
>17482 | value=renderWithHooks(null,workInProgress,Component,props,context,renderExtrationTime);
|^17483 | SETISRENDING(假);
17484 |}//React DevTools读取此标志。
17485 | 
视图编译
开始工作
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:18596
18593 |开关(workInProgress.tag){
18594 |案例不确定成分:
18595 |     {
>18596 |返回安装不确定组件(当前、工作进程、工作进程类型、RenderExtrationTime);
| ^  18597 |     }
18598 | 
18599 |案例懒组件:
视图编译
HtmlUnknowneElement.callCallback
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:188
185 | window.event=windowEvent;
186 |   }
187 | 
>188 |函数应用(上下文,函数);
|^189 | diderro=false;
190 |}//创建一个全局错误事件处理程序。我们使用它来捕获值
191 |//已抛出。此错误处理程序可能会触发更多错误
视图编译
invokeGuardedCallbackDev
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:237
234 |//错误,它将触发全局错误处理程序。
235 | 
236 | evt.initEvent(evtType,false,false);
>237 | fakeNode.调度事件(evt);
| ^  238 | 
239 |如果(windowEventDescriptor){
240 | Object.defineProperty(窗口“事件”,窗口事件描述符);
视图编译
invokeGuardedCallback
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:292
289 |函数invokeGuardedCallback(名称、函数、上下文、a、b、c、d、e、f){
290 | hasError=假;
291 | caughtError=null;
>292 | invokeGuardedCallbackImpl$1.apply(报告者、参数);
293 | }
294 | /**
295 |*与invokeGuardedCallback相同,但它不返回错误,而是存储
视图编译
开始工作1美元
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:23203
23200 |}//再次运行beginWork。
23201 | 
23202 | 
>23203 | invokeGuardedCallback(null、beginWork、null、current、unitOfWork、expirationTime);
| ^  23204 | 
23205 |如果(hasCaughtError()){
23206 | var replayError=clearCaughtError();/`invokeGuardedCallback`有时设置expando`_suppressLogging`。
视图编译
执行工作
H:/ReactJs/Source code/react master/react master/node_modules/react dom/cjs/react dom.development.js:22154
22151 | 
22152 |如果((unitOfWork.mode&ProfileMode)!==NoMode){
22153 | startProfilerTimer(工作单元);
>22154 |下一步=开始工作$1(当前、工作单元、渲染盗版时间$1);
|^22155 | StopperOffilerTimerFrunningandRecordDelta(工作单元,真实);
221
TypeError: Cannot read property 'clientWidth' of undefined
CarouselFlex
H:/ReactJs/Source Codes/react-master/react-master/src/components/Sliders/Carousel.js:9
   6 |   const carouselSlide = document.querySelector('.carousel-slide');
   7 |    const carouselImages = document.querySelectorAll('.carousel-slide img');
   8 |    let counter = 1;   
>  9 |    const size = carouselImages[0].clientWidth;
  10 |    carouselSlide.style.transform = 'translateX(' + (size * counter) + 'px)'
  11 |    
  12 | //    // Similar to componentDidMount and componentDidUpdate:
View compiled
renderWithHooks
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:14803
  14800 |   }
  14801 | }
  14802 | 
> 14803 | var children = Component(props, secondArg); // Check if there was a render phase update
        | ^  14804 | 
  14805 | if (workInProgress.expirationTime === renderExpirationTime) {
  14806 |   // Keep rendering in a loop for as long as render phase updates continue to
View compiled
mountIndeterminateComponent
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:17482
  17479 | 
  17480 |   setIsRendering(true);
  17481 |   ReactCurrentOwner$1.current = workInProgress;
> 17482 |   value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
        | ^  17483 |   setIsRendering(false);
  17484 | } // React DevTools reads this flag.
  17485 | 
View compiled
beginWork
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:18596
  18593 | switch (workInProgress.tag) {
  18594 |   case IndeterminateComponent:
  18595 |     {
> 18596 |       return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderExpirationTime);
        | ^  18597 |     }
  18598 | 
  18599 |   case LazyComponent:
View compiled
HTMLUnknownElement.callCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:188
  185 |     window.event = windowEvent;
  186 |   }
  187 | 
> 188 |   func.apply(context, funcArgs);
      | ^  189 |   didError = false;
  190 | } // Create a global error event handler. We use this to capture the value
  191 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:237
  234 | // errors, it will trigger our global error handler.
  235 | 
  236 | evt.initEvent(evtType, false, false);
> 237 | fakeNode.dispatchEvent(evt);
      | ^  238 | 
  239 | if (windowEventDescriptor) {
  240 |   Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:292
  289 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  290 |   hasError = false;
  291 |   caughtError = null;
> 292 |   invokeGuardedCallbackImpl$1.apply(reporter, arguments);
  293 | }
  294 | /**
  295 |  * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
beginWork$1
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:23203
  23200 | } // Run beginWork again.
  23201 | 
  23202 | 
> 23203 | invokeGuardedCallback(null, beginWork, null, current, unitOfWork, expirationTime);
        | ^  23204 | 
  23205 | if (hasCaughtError()) {
  23206 |   var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
View compiled
performUnitOfWork
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22154
  22151 | 
  22152 | if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
  22153 |   startProfilerTimer(unitOfWork);
> 22154 |   next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
        | ^  22155 |   stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
  22156 | } else {
  22157 |   next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
View compiled
workLoopSync
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22130
  22127 | function workLoopSync() {
  22128 |   // Already timed out, so perform work without checking if we need to yield.
  22129 |   while (workInProgress !== null) {
> 22130 |     workInProgress = performUnitOfWork(workInProgress);
  22131 |   }
  22132 | }
  22133 | /** @noinline */
View compiled
performSyncWorkOnRoot
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:21756
  21753 | 
  21754 | do {
  21755 |   try {
> 21756 |     workLoopSync();
        | ^  21757 |     break;
  21758 |   } catch (thrownValue) {
  21759 |     handleError(root, thrownValue);
View compiled
scheduleUpdateOnFiber
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:21188
  21185 |   // root inside of batchedUpdates should be synchronous, but layout updates
  21186 |   // should be deferred until the end of the batch.
  21187 | 
> 21188 |   performSyncWorkOnRoot(root);
        | ^  21189 | } else {
  21190 |   ensureRootIsScheduled(root);
  21191 |   schedulePendingInteractions(root, expirationTime);
View compiled
updateContainer
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24373
  24370 |   }
  24371 | 
  24372 |   enqueueUpdate(current$1, update);
> 24373 |   scheduleWork(current$1, expirationTime);
  24374 |   return expirationTime;
  24375 | }
  24376 | function getPublicRootInstance(container) {
View compiled
(anonymous function)
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24758
  24755 | 
  24756 | 
  24757 |   unbatchedUpdates(function () {
> 24758 |     updateContainer(children, fiberRoot, parentComponent, callback);
        | ^  24759 |   });
  24760 | } else {
  24761 |   fiberRoot = root._internalRoot;
View compiled
unbatchedUpdates
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:21903
  21900 | executionContext |= LegacyUnbatchedContext;
  21901 | 
  21902 | try {
> 21903 |   return fn(a);
        | ^  21904 | } finally {
  21905 |   executionContext = prevExecutionContext;
  21906 | 
View compiled
legacyRenderSubtreeIntoContainer
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24757
  24754 |   } // Initial mount should not be batched.
  24755 | 
  24756 | 
> 24757 |   unbatchedUpdates(function () {
        | ^  24758 |     updateContainer(children, fiberRoot, parentComponent, callback);
  24759 |   });
  24760 | } else {
View compiled
render
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24840
  24837 |     }
  24838 |   }
  24839 | 
> 24840 |   return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
  24841 | }
  24842 | function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
  24843 |   if (!isValidContainer(containerNode)) {
View compiled
Module../src/index.js
H:/ReactJs/Source Codes/react-master/react-master/src/index.js:9
   6 | import reducer, { initialState } from "./reducer";
   7 | import { StateProvider } from "./StateProvider";
   8 | 
>  9 | ReactDOM.render(
  10 |   <React.StrictMode>
  11 |     <StateProvider initialState={initialState} reducer={reducer}>
  12 |       <App />
View compiled
__webpack_require__
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:784
  781 | };
  782 | 
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 | 
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
fn
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:3421:18
__webpack_require__
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:784
  781 | };
  782 | 
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 | 
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
checkDeferredModules
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 | 
View compiled
Array.webpackJsonpCallback [as push]
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 | 
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
   .carousel-slide{
      display: flex;
      width:100%; // - also I removed it 
      height:500px;
   }
import React, { useState, useRef, useEffect } from "react";
import "./Carousel.css";

const Carousel = () => {
  const [counter, setCounter] = useState(0);
  const [isNextClick, setIsNextClick] = useState(false);
  const [size, setSize] = useState(1);
  const [carouselImages, setCarouselImages] = useState(null);
  const carouselSlideRef = useRef();

  useEffect(() => {
    const images = document.querySelectorAll("img");
    const size_ = images[0].clientWidth;
    setCarouselImages(images);
    setSize(size_);
  }, [counter, size]);

  function showNextItemFlex() {
    carouselSlideRef.current.style.transition = "transform 0.4s ease-in-out";
    const counter_ = counter < carouselImages.length - 1 ? counter + 1 : 0;
    setCounter(counter_);
    setIsNextClick(true);
    carouselSlideRef.current.style.transform = `translateX(${
      -size * counter_
    }px)`;
  }

  function showPreviousItemFlex() {
    carouselSlideRef.current.style.transition = "transform 0.4s ease-in-out";
    const counter_ = counter <= 0 ? carouselImages.length - 1 : counter - 1;
    setCounter(counter_);
    setIsNextClick(false);
    carouselSlideRef.current.style.transform = `translateX(${
      -size * counter_
    }px)`;
  }

  function fireTransitioned() {
    if (carouselImages[counter].id === "lastClone" && !isNextClick) {
      carouselSlideRef.current.style.transition = "none";
      const counter_ = carouselImages.length - 1;
      setCounter(counter_);
      carouselSlideRef.current.style.transform =
        "translateX(" + -size * counter_ + "px)";
    }
    if (carouselImages[counter].id === "firstClone" && isNextClick) {
      carouselSlideRef.current.style.transition = "none";
      const counter_ = 0;
      setCounter(counter_);
      carouselSlideRef.current.style.transform =
        "translateX(" + -size * counter_ + "px)";
    }
  }

  return (
    <>
      <p>{counter}</p>
      <div className="carousel-container">
        {/* <i id="prevBtn" onClick={showPreviousItem}>&#10094;</i>
  <i id="nextBtn" onClick={showNextItem}>&#10095;</i> */}
        <i id="prevBtn" onClick={showPreviousItemFlex}>
          &#10094;
        </i>
        <i id="nextBtn" onClick={showNextItemFlex}>
          &#10095;
        </i>
        <div
          ref={carouselSlideRef}
          className="carousel-slide"
          onTransitionEnd={fireTransitioned}
        >
          <img
            id="lastClone"
            src="https://source.unsplash.com/InR-EhiO_js"
            alt="None"
          />
          <img src="https://source.unsplash.com/gKk9rpyDryU" alt="None " />
          <img src="https://source.unsplash.com/VFGEhLznjPU" alt="None" />
          <img
            id="firstClone"
            src="https://source.unsplash.com/InR-EhiO_js"
            alt="None"
          />
        </div>
      </div>
    </>
  );
};

export default Carousel;