ReactJs全球帮手功能 [英] ReactJs Global Helper Functions

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

问题描述

问题:
我有很多小帮助函数,它们不一定需要存在于一个组件中(或者也许它们可以,但是它们会让这个组件臃肿得很多代码)。我懒惰的一面只是想让这些都成为组件可以调用的某种全局函数。我真的想要制作出好的ReactJs代码。

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



基本示例:

函数helperfunction1(a,b){
//做了一些工作
返回someValue;
}

函数helperfunction2(c,d){
//做一些工作
返回someOtherValue;
}

函数helperfunction3(e,f){
//做一些工作
返回anotherValue;
}

函数helperfunction4(a,c){
//做了一些工作
return someValueAgain;



var SomeComponent =
React.createClass({

//有一堆方法

//使用一些辅助函数

render:function(){

}

});

var SomeOtherComponent =
React.createClass({

//有一堆方法

//使用一些辅助函数

render:function(){

}

});


解决方案

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



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


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.

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?

Basic Example:

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

        }

    });

解决方案

You can use a module-bundling tool like Webpack or Browserify for that. Put your reusable functions in a CommonJS module.

Do not use Mixins, they will probably be deprecated in next versions of React as there's no standard way to declare mixins in React with ES6 syntax and they prefer to wait for ES7 that will probably standardize mixins. And there's no point coupling your reusable code to React unless it uses React lifecycle's methods.

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

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