简体   繁体   English

如何在 React 中存储函数

[英]how to store a function in React

I wrote a function that checks the width of the window (for keeping a component responsive):我编写了一个检查窗口宽度的函数(用于保持组件响应):

  handleResize = () => this.setState({ windowWidth: window.innerWidth });
  handleEvent = () => window.addEventListener("resize", this.handleResize);

  componentDidMount = () => this.handleEvent();
  componentWillUnmount = () => this.handleEvent();

In case I want to reuse this code in other files, is there any way I can save this code and just reuse it everywhere I want?如果我想在其他文件中重用此代码,有什么方法可以保存此代码并在我想要的任何地方重用它?

Best way to do is using helpers.最好的方法是使用助手。 You can create a simple file, say helpers.js and place somewhere inside the src folder.您可以创建一个简单的文件,比如helpers.js并将其放在src文件夹中的某个位置。 It should contain something like this:它应该包含如下内容:

export const HandleResize = callBack => window.addEventListener("resize", callBack);

In this above code, I have given a callBack parameter, because you're trying to access the state of the component that calls it.在上面的代码中,我给出了一个callBack参数,因为您正在尝试访问调用它的组件的状态。 So you'll be sending it from the component.所以你将从组件发送它。

And you can use it on your other files something like this way:你可以像这样在你的其他文件上使用它:

import React from "React";
import { HandleResize } from "../helpers";

You can use helper functions like Praveen Kumar Purushothaman mentioned but in this case you probably want to use CSS media queries for it.您可以使用提到的 Praveen Kumar Purushothaman 等辅助函数,但在这种情况下,您可能希望使用 CSS 媒体查询。 Have a look into CSS modules.看看 CSS 模块。 Also, your this might not refer to what you think you are referring when using an arrow function, if you still want to use this prefer to use the normal function defintion: function () {...} .此外,您的this可能不是指您在使用箭头函数时所指的内容,如果您仍然想使用this更喜欢使用普通函数定义: function () {...}

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

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