Reactjs react中useCallback的钩子调用无效
我遇到了一个问题,我尝试在一个类中转换此示例中的函数: 但是,我犯了一个错误。代码如下:Reactjs react中useCallback的钩子调用无效,reactjs,Reactjs,我遇到了一个问题,我尝试在一个类中转换此示例中的函数: 但是,我犯了一个错误。代码如下: import React, { Component, useCallback } from "react"; import Gallery from "react-photo-gallery"; import Carousel, { Modal, ModalGateway } from "react-images"; class Gallerie extends Component { const
import React, { Component, useCallback } from "react";
import Gallery from "react-photo-gallery";
import Carousel, { Modal, ModalGateway } from "react-images";
class Gallerie extends Component {
constructor(props){
super(props)
this.state = {
currentImage: 0,
setCurrentImage: 0,
viewerIsOpen: false,
setViewerIsOpen: false,
}
}
render(){
const openLightbox = useCallback((event, { photo, index }) => {
this.state.setCurrentImage(index);
this.state.setViewerIsOpen(true);
}, []);
const closeLightbox = () => {
this.state.setCurrentImage(0);
this.state.setViewerIsOpen(false);
};
return (
<div>
<Gallery photos={this.props.photos} onClick={() => openLightbox} />
<ModalGateway>
{this.state.viewerIsOpen ? (
<Modal onClose={() =>closeLightbox}>
<Carousel
currentIndex={this.state.currentImage}
views={this.props.photos.map(x => ({
...x,
srcset: x.srcSet,
caption: x.title
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
}
}
export default Gallerie;
以下是问题和我得到的:
我不知道useCallBack是做什么的。如果我只是复制/粘贴示例,它就可以工作。问题是,可变照片被用作道具,因为每个用户的照片会有所不同。所以我需要把它转换成其他组件。如果我使用像这个例子一样的函数,我不能使用道具
感谢您的帮助。您正在基于类的组件中使用挂钩。首先将其转换为功能组件
const Gallerie = props =>{
const [state, setState] = useState({
currentImage: 0,
setCurrentImage: 0,
viewerIsOpen: false,
setViewerIsOpen: false,
})
const openLightbox = useCallback((event, { photo, index }) => {
setState({...state, setCurrentImage: index, setViewerIsOpen: true});
}, []);
const closeLightbox = () => {
setState({...state, setCurrentImage: 0,setViewerIsOpen: false })
};
return (
<div>
<Gallery photos={props.photos} onClick={() => openLightbox} />
<ModalGateway>
{state.viewerIsOpen ? (
<Modal onClose={() =>closeLightbox}>
<Carousel
currentIndex={state.currentImage}
views={props.photos.map(x => ({
...x,
srcset: x.srcSet,
caption: x.title
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
}
谢谢然后如何将其导出到主组件中使用?这正是使用类组件的方式。导出默认Gallerie通过复制/粘贴您的代码+导出默认值,我确实收到了相同的错误消息…您正在错误地更新状态,我错过了!更新答案。现在试试