1

我正在尝试使用 webtorrent 桌面的基本代码,您可以在这里查看我的分支的代码: https ://github.com/refreex/webtorrent-desktop

它使用 Node.js 和 Electron

我面临的问题是我创建了一个名为的新控制器playlists-controller.js,并且有一个名为的函数getAllPlaylists,我需要在名为的 React 组件中使用它playlists-list.js

我正在尝试使用以前使用过的相同概念,但我不明白如何从我的控制器在反应组件中调用该函数。

有一个名为的文件main.js,其中列出了控制器具有的所有功能,如下所示:

  //Playlists
  'createPlaylist': (name) => controllers.playlists().createPlaylist(name),
  'addAlbumToPlaylist': (infoHash, files) => controllers.playlists().addAlbumToPlaylist(infoHash, files),
  'addSongToPlaylist': (infoHash, file) => controllers.playlists().addSongToPlaylist(infoHash, file),
  'getAllPlaylists': () => controllers.playlists().getAllPlaylists(),

沿着应用程序有很多使用调度程序的调用,但我认为主要用于事件,但我不确定。

所以基本上在页面中playlists-list.js我需要调用其中的getAllPlaylists函数playlists-controller.js

这样做的好方法是什么?

提前致谢。

4

1 回答 1

0

This can be done in two ways. One, passing the function as props to that component or we can export the getAllPlaylist method and use it by importing into the playlists-lists component. I hope this will help you solve your issue.

Method 1:

 class PlaylistController extends React.Component {

    getAllPlaylist = () => {
    alert('Do Something Here As Per Your Requirement!')
    }

    render () {
    return (
        <container>
            <PlaylistList sendFunction={this.getAllPlaylist} />
        </container>
    )
    }
}

class PlaylistList extends React.Component {

render () {
return (
    <div>
        <button onClick={this.props.sendFunction}>Click Here To Call Playlist-list Function</button>
    </div>
)
}

}

Method 2:

 class PlaylistController extends React.Component {
   export const getAllPlaylist = ()=>{
    //do something as per the requirement
   }
 }


import {getAllPlaylist} from './playlistController'

class PlaylistList extends React.Component {


    handleClick = () => {
    getAllPlaylist(); 
    }
    render () {
    return (
        <div>
            <button onClick={this.handleClick}>Click Here To Call Playlist-list Function</button>
        </div>
    )
    }

}
于 2019-02-08T05:33:58.167 回答