【发布时间】:2020-08-01 01:20:56
【问题描述】:
在寻找正确答案几个小时后,我无处可寻。我会尽力解释我的情况。我的网站上有一个图像轮播,我想在用户触发并单击图像时打开它。所以基本上我的网站上有 5 张图片,无论用户选择哪个图片,都应该在图片轮播中打开它。一切都很完美,我做到了这一点。所以我有一个页面文件,其中包含轮播所在页面的所有代码。然后我有一个仅用于图像部分组件的文件,我在其中发送 handleViewPhotosClick 函数(此函数打开图像轮播)作为来自主页的道具。所以在这个文件中,我检测到哪个图像被点击,并将其编号发送到具有更新状态的图像轮播组件(它是一个用于打开正确图像的数字)。
但问题是我不能在一次点击中传递handleViewPhotosClick 和handleSelectedImage,或者我只是不知道正确的语法。
我不会写完整的代码,我只会复制它。
ListingPage(主页):
export default class ListingPage extends Component {
constructor(props) {
this.state = {
imageCarouselOpen: false
};
}
render() {
const handleViewPhotosClick = (e) => {
e.stopPropagation();
this.setState({
imageCarouselOpen: true // This opens carousel
});
};
return (
<SectionImages
handleViewPhotosClick={handleViewPhotosClick} {/* Passing handleViewPhotosClick to SectionImages */}
/>
)
}
}
SectionImages(图片部分):
export default class SectionImages extends Component {
constructor(props) {
this.state = {
selectedImage: null,
number: 0
}
}
handleSelectedImage(number) {
this.setState({ selectedImage: number });
}
render() {
const { handleViewPhotosClick } = this.props;
const imageItem = (itemClass, imagePath, number) => {
return (
// Is there a way to append handleViewPhotosClick to the bellow onClick function?
<div className={itemClass} onClick={() => { this.handleSelectedImage(number) }}>
<img src={imagePath} alt={number} />
</div>
);
};
return (
<div>
{imageItem(itemClass, imagePath, 0 )} {/* 0 stands for unique image number I pass */}
{imageItem(itemClass, imagePath, 1)} {/* 1 stands for unique image number I pass */}
<Modal>
<ImageCarousel selectedImage={this.state.selectedImage} /> {/* passing the props to the image carousel component which I then use in ImageCarousel constructor */}
</Modal>
</div>
)
}
}
所以基本上我正在尝试将handleViewPhotosClick 添加到imageItem onClick 函数中。我知道我们可以在一次 onClick 调用中传递多个函数,但我如何传递 props + 函数。希望我足够清楚。我是 React 的新手,所以这可能是我的错误方法,任何帮助都意义重大。谢谢!
【问题讨论】:
-
你想通过什么道具?
-
你不能这样做:onClick={() => { this.handleSelectedImage(number) ; handleViewPhotosClick();}} ?
-
只需在
handleSelectedImage中添加this.props.handleViewPhotosClick() -
@wentjun 你好!好的,所以我将 handleViewPhotosClick (在 ListingPage 中它是一个函数,然后我作为道具传递给 SectionImages)然后我想在 SectionImages 内的 imageItem 函数的一个 onClick 事件中包含 handleViewPhotosClick 和新的 handleSelectedImage。
-
@GalAbra 感谢您的解决方案!当我添加它并单击图像时,出现此错误:“TypeError: Cannot read property 'stopPropagation' of undefined”
标签: javascript html node.js reactjs