我正在尝试在React.js中构建一个图库,到目前为止一切都很顺利。
在库中我正在创建缩略图对象 - 点击这将激活“迷你画廊”,其中包含来自特定项目的所有图片和项目说明。然而,为了回到主画廊,我在“迷你画廊”中创建了“关闭”按钮,附带处理程序。
缩略图点击工作,但关闭按钮没有。请参阅下面的代码。
我将非常感谢您的帮助!
这是主画廊:
import React from 'react';
import Thumbnail from '../components/Thumbnail';
export default class Drawings extends React.Component {
render () {
const linkPrefix = "./life/";
const imageS = ".800.jpg";
const imageL = ".jpg";
const lifePics = [
{
name: "One",
filename: [
"lifedrawing1",
],
descr: "one",
},
{
name: "Two",
filename: [
"lifedrawing2",
"lifedrawing2ed",
"lifedrawing2ed2",
],
descr: "two",
},
{
name: "Three",
filename: [
"lifedrawing3",
],
descr: "three",
},
]
return (
<div id="Drawings" className="container row around wrap">
{lifePics.map(
(picture, i) =>
<Thumbnail
key={i}
linkPrefix={linkPrefix}
filename={picture.filename}
imageS={imageS}
imageL={imageL}
/>
)}
</div>
);
}
}
import React from 'react';
export default class Thumbnail extends React.Component {
constructor(props) {
super(props);
this.state = {
viewerDisplay: "hidden",
};
}
thumbnailClick(event) {
this.setState({
viewerDisplay: "visible",
});
}
closeViewer(event) {
this.setState({
viewerDisplay: "hidden",
});
}
render () {
const thumbnailStyle = {
width: '45%',
height: '300px',
backgroundImage: 'url('+this.props.linkPrefix + this.props.filename[0]+this.props.imageS+')',
backgroundSize: 'cover',
marginBottom: '10px',
cursor: 'pointer',
};
var viewerStyle = {
position: "absolute",
top: "300px",
right: "50px",
bottom: "10px",
left: "50px",
visibility: this.state.viewerDisplay,
background: "black",
cursor: "auto",
};
const viewerColStyle = {
width: "50%",
height: "100%",
}
return (
<div
className="thumbnail container col between"
style={thumbnailStyle}
onClick={this.thumbnailClick.bind(this)}
>
<div
id="Viewer"
className="viewer container row between"
style={viewerStyle}
>
<div
id="PicList"
className="container col around"
style={viewerColStyle}
>
Thumbnails
{//map function for thumbnails of particular gallery
}
</div>
<div
id="ProjectDescr"
className="container col around"
style={viewerColStyle}
>
Project Descr
</div>
<button
onClick={this.closeViewer.bind(this)}
>CLOSE</button>
</div>
</div>
);
}
}
答案 0 :(得分:1)
您应该将event.stopPropagation()
添加到closeViewer
功能,以防止点击事件传播到缩略图 div元素
closeViewer(event) {
event.stopPropagation();
this.setState({
viewerDisplay: "hidden",
});
}
以下是没有stopPropagation的示例
<body>
<div onclick="clickDiv()">
<button onclick="clickButton()">Test</button>
</div>
<script>
function clickButton() {
alert('clickButton');
}
function clickDiv() {
alert('clickDiv');
}
</script>
</body>
以下是stopPropagation
的示例
<body>
<div onclick="clickDiv()">
<button onclick="clickButton(event)">Test</button>
</div>
<script>
function clickButton(e) {
e.stopPropagation();
alert('clickButton');
}
function clickDiv() {
alert('clickDiv');
}
</script>
</body>
答案 1 :(得分:0)
您应该在构造函数中绑定您的单击处理程序,或者使其成为箭头函数以传递上下文:
thumbnailClick = (event) => {
this.setState({
viewerDisplay: "visible",
});
}