나는 후크를 배우고 ref 객체와 관련하여 다음 문제에 직면하고 있습니다. 이 스 니펫을 실행할 때 :
const [offset, setOffset] = useState(0);
const [maxX, setMaxX] = useState(0);
const itemRef = React.createRef();
useEffect(() => {
if (itemRef.current.childElementCount > 0) {
setMaxX((itemRef.current.childElementCount / 3) *
itemRef.current.offsetWidth - itemRef.current.offsetWidth)
}
}, [])
useEffect(() => {
itemRef.current.style.transform = `translateX(-${offset}px)`
}, [offset])
const shiftSliderRight = () => {
setOffset(offset => offset + itemRef.current.offsetWidth);
}
return (
<div>
<div className='page-new-arrivals'>
<img src={'./static/arrivals_ss19.png'} alt='Arrivals'/>
<div className='page-new-arrivals__slider_container'>
<div ref={itemRef} className='page-new-arrivals__slider'>
<Link to="/itemPage"><Item imgLink='./static/tshirt1.png'/></Link>
<Item imgLink='./static/tshirt2.png'/>
<Item imgLink='./static/tshirt3.png'/>
<Item imgLink='./static/tshirt3.png'/>
<Item imgLink='./static/tshirt1.png'/>
<Item imgLink='./static/tshirt2.png'/>
</div>
<button onClick={shiftSliderRight}/>
</div>
</div>
</div>
)
}
나는 Uncaught TypeError: Cannot read property 'style' of null
줄을 얻는다itemRef.current.style.transform = `translateX(-${offset}px)
goog dev 도구에서이 줄에 중단 점을 배치하면 실제로 null이 아니며 모든 것이 정상이며 렌더링이 완료되면 오류가 없음을 알 수 있습니다. 왜 그래야만하지?
선은 const itemRef = React.createRef();
각각 ... 렌더링 같은 사용하기에 다른 심판 개체를 만들고 변경할 심판 :
const itemRef = useRef();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다