ReactJs 全局帮助函数 [英] ReactJs Global Helper Functions

查看:23
本文介绍了ReactJs 全局帮助函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我有很多小型辅助函数,它们不一定需要存在于组件中(或者它们可以,但它们会使该组件因大量代码而臃肿).我懒惰的一面只是想让这些都只是组件可以调用的某种全局函数.我真的很想制作好的 ReactJs 代码.

Issue: I have a lot of small helper functions that don't necessarily need to live in a component(or maybe they can but they will make that component bloated with a lot of code).My lazy side just wants to just let those all just be some sort of global functions that the components can call.I really want to make good ReactJs code.

问题:Reactjs 中全局辅助函数的最佳实践是什么?我应该强迫它们进入某种组件还是只是将它们推到其他组件中?

Question: What are the best practices in terms of global helper functions in Reactjs? Should I force them into some sort of component or just shove them into the other components?

基本示例:

function helperfunction1(a, b) {
    //does some work
    return someValue;
}

function helperfunction2(c, d) {
    //does some work
    return someOtherValue;
}

function helperfunction3(e, f) {
    //does some work
    return anotherValue;
}

function helperfunction4(a, c) {
    //does some work
    return someValueAgain;
}


var SomeComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

var SomeOtherComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

推荐答案

你可以从一个文件中导出多个函数,本身不需要 React:

You can export multiple functions from a file, no React needed per se:

Helpers.js:

Helpers.js:

export function plus(a, b) {
  return a + b;
}

export function minus(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  return a / b;
}

然后你就可以导入你需要的函数了:

You can then import the functions you need:

import { multiply, divide } from './Helpers'

这篇关于ReactJs 全局帮助函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆