39

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

5 回答 5

46

你可以从一个文件中导出多个函数,本身不需要 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'
于 2018-03-27T14:04:20.437 回答
9

为此,您可以使用WebpackBrowserify 之类的模块捆绑工具。将您的可重用函数放在 CommonJS 模块中。

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

于 2015-05-13T15:06:53.747 回答
1

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

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

var MyCommonFunc = {
    helperFunction1: function() {
       alert('herper function1');
    },
    doSomething: function(){
        alert('dosomething');
    }
}

var Hello = React.createClass({
    mixins: [MyCommonFunc],
    render: function() {
        this.doSomething();
        return <div onClick={this.helperFunction1}>Hello {this.props.name} </div>;
    }
});

React.render(<Hello name="World" />, document.getElementById('container'));
于 2015-05-13T03:39:00.623 回答
1

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

var YourComponent = React.createClass({

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

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

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

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

于 2016-03-18T14:54:13.353 回答
0

使用 React 上下文来做这样的事情。它是为这个确切的用例而构建的;文档:https ://reactjs.org/docs/context.html

于 2022-02-20T13:21:25.407 回答