[英]Rendering a component onClick in React
我对React和javascript一般而言是新的。 这样的问题。
我有一个在React组件中显示的图像列表。 我要实现的目标是定义一种方法来处理这些图像中的任何onClick方法,并将新组件呈现为覆盖图。 这是我的代码。
class Viewer extends React.Component{
constructor(props){
super(props);
this.state = {
images : ImageList
};
}
componentDidMount(){
}
handleClick(mediaId, event){
event.preventDefault();
render(){
<MyNewComponent mediaId=mediaId />
}
}
render(){
return (
<div className="row">
<div className="image-viewer">
<ul className="list-inline">
{this.state.images.map(function (image) {
return (<li key={image.mediaId}><a href="#" onClick={this.handleClick.bind(image.mediaId, event)}><img src={image.src}
className="img-responsive img-rounded img-thumbnail"
alt={image.mediaId}/></a></li>);
})}
</ul>
</div>
</div>
);
}
}
export default Viewer;
这显然是错误的,并引发了许多错误。 有人可以指出我正确的方向。
这里是如何处理click
事件并显示覆盖图
class Viewer extends React.Component{
constructor(props){
super(props);
this.state = {
images : ImageList,
mediaId : 0
};
// Bind `this`
// See "Binding to methods of React class" link below
this.handleClick = this.handleClick.bind(this);
}
componentDidMount(){ }
handleClick(event){
event.preventDefault();
// Get the value of the `data-id` attribute <a data-id="XX">
var mediaId = event.currentTarget.attributes['data-id'].value;
// Set the state to re render
this.setState({ mediaId }); // ES6 shortcut
// this.setState({ mediaId: mediaId }); // Without shortcut
}
render(){
// Set a variable which contains your newComponent or null
// See "Ternary operator" link below
// See "Why use null expression" link below
var overlay = this.state.mediaId ? <MyNewComponent mediaId={this.state.mediaId} /> : null;
return (
<div className="row">
<div className="image-viewer">
{ overlay }
<ul className="list-inline">
{this.state.images.map(image => {
return (<li key={image.mediaId}><a href="#" onClick={this.handleClick} data-id={image.mediaId}><img src={image.src}
className="img-responsive img-rounded img-thumbnail"
alt={image.mediaId}/></a></li>);
}).bind(this)}
</ul>
</div>
</div>
);
}
}
export default Viewer;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.