简体   繁体   English

如何从 React + Typescript 中另一个文件中的导入组件调用 function?

[英]How to call a function from an imported component in another file in React + Typescript?

I'm currently trying to hook up a button in my homepage to go to another link, and I want to make use of some functions from another file.我目前正在尝试将我主页中的一个按钮连接到 go 到另一个链接,并且我想利用另一个文件中的一些功能。 Currently, the functions I want to use are in a SettingsMenu.tsx file and the component looks like this:目前,我要使用的功能位于SettingsMenu.tsx file中,组件如下所示:

export class SettingsMenu extends Component<
  SettingsMenuProps,
  SettingsMenuState
> {
  constructor(props: SettingsMenuProps) {
    //Lots of code 
  }

  gotoExternalLink = (e: React.MouseEvent, url: string) => {
    window.open(url, '_blank', 'noopener noreferrer');
    this.hideSettingsMenu(e);
  };


//More code 

}

And in my homepage, I've already done import SettingsMenu from './SettingsMenu' and attempted to hook up my button wiith the gotoExternalLink function, which I'm having difficulty doing.在我的主页中,我已经完成了import SettingsMenu from './SettingsMenu'并尝试使用gotoExternalLink function 连接我的按钮,但我很难做到。 I have tried the following:我尝试了以下方法:

Button variant="contained" className="support-button" 
          onClick={gotoExternalLink(e,"https://app.clovergive.com/App/Form/c226e457-5e64-4f75-8cbb-e8cba99138f4" )}>
          Support Us
        </Button>

Can anyone provide some support or help?任何人都可以提供一些支持或帮助吗?

Standing at one component and calling a method from another component is not the way React data flow works.站在一个组件上并从另一个组件调用方法不是 React 数据流的工作方式。

If you simply want to go to external link, you could extract that logic into a utils file and call it in each event handler.如果您只是想 go 到外部链接,您可以将该逻辑提取到一个 utils 文件中并在每个事件处理程序中调用它。

//in utils.ts
export const goToExternalLinkUtil = (url: string) => {
  window.open(url, '_blank', 'noopener noreferrer');
}

// in HomePage.tsx
<Button variant="contained" 
    className="support-button" 
    onClick={() => { gotoExternalLinkUtil("https://app.clovergive.com/App/Form/c226e457-5e64-4f75-8cbb-e8cba99138f4");}
 >
   Support Us
 </Button>

In case you would like to go to extarnal link and then hide the setting menu, you might want to lift up the state of isSettingMenuOpen to the nearest ancestor of SettingMenu and Homepage .如果您想 go 到外部链接然后隐藏设置菜单,您可能需要将 isSettingMenuOpenisSettingMenuOpenSettingMenuHomepage的最近祖先。

Another suggestion is using Redux to manage all the state in one centralized place.另一个建议是使用Redux在一个集中位置管理所有 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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