在React中渲染组件onClick

时间:2016-11-01 17:07:34

标签: javascript reactjs javascript-events event-handling

我对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;

这显然是错误的,并引发了一堆错误。有人能指出我正确的方向。

1 个答案:

答案 0 :(得分:2)

此处如何处理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;

文档