我有一个函数,每当单击子组件中的特定按钮时,我都会在父组件中运行该函数。我正在使用反应钩子进行状态管理。
单击的按钮是子组件中的最后一个按钮,我尝试从父组件调用的函数是onClickHandling
。
父组件:
const SearchPage = () => {
const [searchText, setSearchTerm] = useState('');
const [image, setImage] = useState([]);
const [isLoaded, setIsLoaded] = useState(false);
const [isNext, setIsNext] = useState(false);
const [nextPageIndex, setNextPageIndex] = useState(1);
const [isHidden, setIsHidden] = useState(true);
const onInputChange = (e) => {
setSearchTerm(e.target.value);
};
const getImages = () => {
fetchImages(nextPageIndex, searchText)
.then((data) => {
setImage(data.data.results);
setIsLoaded(false);
});
};
const onSubmitHandler = (e) => {
setImage([]);
e.preventDefault();
setNextPageIndex(1);
getImages();
setIsLoaded(true);
setIsHidden(false);
};
const onClickHandling = () => {
setIsNext(true);
setNextPageIndex(parseInt(nextPageIndex + 1, 10));
};
if (isNext === true) {
fetchImages(nextPageIndex, searchText)
.then((data) => {
const result = data.data.results;
setImage(image.concat(result));
setIsLoaded(false);
});
setIsNext(false);
}
return (
<React.Fragment>
<SearchBar
className="search-bar"
onSubmitHandler={onSubmitHandler}
onInputChange={onInputChange}
searchText={searchText}
/>
<div className="image-container">
{image && (
<ImageList
image={image}
isLoaded={isLoaded}
isHidden={isHidden}
onClickHandler={onClickHandling}
/>
)}
</div>
</React.Fragment>
);
};
export default SearchPage;
子组件:
const ImageList = ({
image, isLoaded, isHidden, onClickHandling,
}) => {
const [imageIndex, setImageIndex] = useState();
const [isOpen, setIsOpen] = useState('false');
if (isLoaded) {
return (
<div className="spinner">
<ReactLoading type="spin" color="blue" />
</div>
);
}
const onClickHandler = (e) => {
setIsOpen(true);
setImageIndex(parseInt((e.target.id), 10));
};
const imgs = image.map((img, index) => (
<img
id={index}
key={img.id}
src={img.urls.small}
onClick={onClickHandler}
/>
));
if (imgs.length === 0) {
return (
<p>No images</p>
);
}
if (isOpen === true) {
return (
<Lightbox
onCloseRequest={() => setIsOpen(false)}
mainSrc={image[imageIndex].urls.regular}
onMoveNextRequest={() => setImageIndex((imageIndex + 1) % image.length)}
onMovePrevRequest={() => setImageIndex((imageIndex + image.length - 1) % image.length)}
nextSrc={image[(imageIndex + 1) % image.length].urls.regular}
prevSrc={image[(imageIndex + image.length - 1) % image.length].urls.regular}
imageTitle={image[imageIndex].alt_description}
imageCaption={`By ${image[imageIndex].user.name}`}
/>
);
}
return (
<React.Fragment>
{imgs}
{!isHidden && <Button onClick={onClickHandling}>Click me</Button> }
</React.Fragment>
);
};
export default ImageList;
用于将函数属性从父组件传递到子组件的名称中有一个拼写错误。
<ImageList
image={image}
isLoaded={isLoaded}
isHidden={isHidden}
onClickHandling={onClickHandling}// <-- Here.
/>