【问题标题】:how to create a function file in react [duplicate]如何在反应中创建函数文件[重复]
【发布时间】:2021-10-17 07:56:52
【问题描述】:

如何创建一个函数文件,在其中我可以在一个文件中编写所有函数并在我的组件上调用它。就像在 PHP 中一样,我们创建一个函数文件并使用 require(function.php) 来编写所有函数。我想知道如何为我的项目创建这种类型的帮助程序/函数文件。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

在 js 文件中,例如 helpers.js,您声明函数并添加“导出”。

// helpers.js
export const counter = (a,b) => {
  const sum = a+b
  return sum
}

在要使用计数器功能的文件中导入它。

// App.js

import { counter } from "./helpers.js"

const App = () => {
  ... 
  useEffect(()=>{
    counter(2,3)
  },[])
}

  return(
    <div>
    </div>
  )

【讨论】:

    【解决方案2】:

    在你的反应组件中

    import specialFunctions from './specialFunctions'
    ...
    specialfunctions.customFunction(something)
    
    

    在你的函数文件中

    //specialFuncions.js
    const specialFunctions = () => {
    
      customFunction = (something) => { 
        ...
        return somethingElse
      }
    
      customFunction2 = (something) => { 
        ...
        return somethingElse
      }
    
      return {
        customFunction,
        customFunction2
      }
    }
    export default specialFunctions();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2020-10-16
      • 2021-02-09
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多