[英]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.