【发布时间】:2021-07-29 11:06:33
【问题描述】:
我有一个反应类组件,我试图将左右滚动按钮添加到水平滚动。以this接受的SO回答为例:
...
render() {
const buttonRight = document.getElementById('slideRight');
const buttonLeft = document.getElementById('slideLeft');
buttonRight.onclick = function () {
document.getElementById('container').scrollLeft += 20;
};
buttonLeft.onclick = function () {
document.getElementById('container').scrollLeft -= 20;
};
return (
<div>
<button id="slideLeft" type="button">Slide left</button>
<CardGroup id="container" className="card-group-scroll">
{items && items.map(item =>
<Card key={item.itemNumber} tag="a" onClick={() => handleClick()} style={{ cursor: "pointer" }}>
<CardHeader tag="h3">Featured</CardHeader>
<CardImg top className="card-picture" src={"data:image/png;base64," + decompressToBase64(item.images[0]?.compressedImageData)} id={item.itemNumber + "Img"} alt={item.itemNumber} />
<CardBody className="card-body">
<CardTitle tag="h5">{item.itemNumber}</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">{item.categoryName}</CardSubtitle>
<CardText className="card-description">{item.itemDescription}</CardText>
</CardBody>
<CardFooter className="text-muted">{formatter.format(item.price)}</CardFooter>
</Card>
)}
</CardGroup>
<button id="slideRight" type="button">Slide right</button>
</div>
);
}
...
...但我收到此错误:
TypeError: buttonRight 为空
...在这条线上buttonRight.onclick = function () {
【问题讨论】:
-
您正在从普通方法复制答案,您正在使用 React,它是查询 DOM 的反模式,为此使用专用 API,例如
createRef。请阅读 React 文档中的 Refs 和 DOM 部分。 -
我认为您正在尝试在 render() 函数完成之前访问该按钮。应该有功能允许您在渲染后访问它。 componentDidMount 也许?
标签: javascript reactjs