简体   繁体   中英

How can I pass a click event from a parent to child elements in React? [ c ]

When clicking on the ancestry tag, I want the links below to open using window.open().

I know that props can easily be passed to children but this does not help.

The child elements looks like this:

import React from 'react';

class FramePageFaveTagFave extends React.Component {

  constructor(props) {
    super(props);
  }

  bookmarkClicked (url) {
    window.open(url, '_blank')
  }

  render () {
    let bm = this.props.bookmark;
    let tagClicked = this.props.tagClicked;

    return (
      <div className='bookmark_div' id={bm.id + 'a'} onClick={() => {this.bookmarkClicked(bm.url)}} >
        <img className='bookmark_image' id={bm.id + 'c'} src={'../_favicons/' + bm.favicon_local}/>
        <a className='bookmark_link' id={bm.id + 'b'} href={bm.url} target='_blank'
          onClick={()=>{e.preventDefault();}}>
          {bm.title}
        </a>
      </div>
    );
  }
}

export default FramePageFaveTagFave;

A good rule of thumb is to think in callbacks when doing this sort of work. The parent can pass a prop down called onBookmarkClicked which is a function that takes a url . Maybe this:

onBookmarkCalled(url) {
   window.open(url, '_blank')
}

<ChildBookmark onBookMarkCalled={this.onBookmarkCalled} />

And you do the exact same thing in the child except instead of this.bookmarkClicked you can do onClick={() => this.props.onBookmarkClicked(url)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM