简体   繁体   中英

react js trigger function from any other component

I have a component that basically loads a video in an overlay using JW Player (simplified example below).

import React, { Component } from 'react'
import ReactJWPlayer from 'react-jw-player'

class VideoPopup extends Component {

render() {
    return (            
        <div id="video">
            <ReactJWPlayer 
              playerId='video-player'
              playerScript='https://content.jwplatform.com/libraries/vr6ybmGf.js'
              file='path to video file'
            />
        </div>

    )
  }
}

export default VideoPopup;

I would like the component to sit directly in the root of my app, but I need to be able to display it when called from ANY other component - this might be a child component, a child of a child, a sibling etc. etc. I was hoping to be able to call it and pass the video file reference simply like below:

<button onClick={somehow show video popup}>show video popup</button>

I understand how to do this easily if there is a direct parent-child relationship, but not if I want to place the link in a variety of different components; I hope someone can point me in the right direction.

If you want to get rid of the parent-children relationships when it comes to actions, use an event manager like Redux ( react-redux ). It is pretty standard an becomes necessary as your app grows anyway.

The principle is that wherever you place your link, it will fire an "action" on click, which is sent to a global dispatcher that other components listen to for changes.

Multiple ways to do this

  • You can define a function that controls the show/hide functionality of the video player in the app component itself and pass it down as a prop to all the components where the event can be fired.
  • Use Redux . This is the ideal choice. You just have to dispatch an action from anywhere in your app and the corresponding reducer will take care of the functionality.
  • Using a global function (not recommended).

Please comment if you need more explanation.

You can try to make global function and call it wherever you want.

showVideoPopup () {
    ReactDOM.render(
        <VideoPopup />,
        document.getElementById('popupHolder')
    );
}

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