ReactJs全球助手功能

时间:2015-05-13 03:30:08

标签: function components reactjs global-methods

问题: 我有很多小帮手功能,不一定需要住在一个组件中(或者他们可以,但他们会用很多代码使这个组件臃肿)。我懒惰的一方只是想让那些全部只是某些组件可以调用的全局函数。我真的想要制作好的ReactJs代码。

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

基本示例:

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 () {

        }

    });

4 个答案:

答案 0 :(得分:8)

您可以使用模块捆绑工具,例如 Webpack Browserify 。 将可重用的函数放在CommonJS模块中。

不要使用Mixins ,它们可能会在下一版本的React中被弃用,因为没有标准方法在React中使用ES6语法声明mixins,他们更愿意等待可能标准化mixin的ES7 。除非使用React生命周期的方法,否则将可重用代码与React耦合是没有意义的。

答案 1 :(得分:8)

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

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;
}

然后您可以导入所需的功能:

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

答案 2 :(得分:1)

您可以使用modulejs。 或者您可以使用mixins(https://facebook.github.io/react/docs/reusable-components.html#mixins

mixins的示例:https://jsfiddle.net/q88yzups/1/

{{1}}

答案 3 :(得分:0)

另一种选择,如果您不想拆分成单独的模块,您可以在父组件中创建一个私有方法,如下所示,并在此组件中自由使用或通过props传递给子组件。

var YourComponent = React.createClass({

    globalConfig: function() {
        return {
            testFunc: function () {
                console.log('testing...');
            },
        };
    }(),

    ......
    render: function() {
        this.globalConfig.testFunc(); // use directly

        <ChildComponent globalConfig={this.globalConfig.testFunc} /> // pass to child
    .....

所有未经测试的,但这就是想法......

相关问题