Nic*_*eda 28 components function global-methods reactjs
问题:我有很多小辅助函数,它们不一定需要存在于一个组件中(或者可能它们可以但是它们会使该组件膨胀很多代码).我懒惰的一方只是想让那些全部只是某些组件可以调用的全局函数.我真的想要制作好的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 () {
}
});
Run Code Online (Sandbox Code Playgroud)
Mic*_*iel 15
您可以从文件中导出多个功能,本质上不需要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;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以导入所需的功能:
import { multiply, divide } from './Helpers'
Run Code Online (Sandbox Code Playgroud)
您可以使用Webpack或Browserify之类的模块捆绑工具.将可重用功能放在CommonJS模块中.
不要使用Mixins,它们可能会在下一版本的React中被弃用,因为没有标准方法在React中使用ES6语法声明mixins,他们更愿意等待可能标准化mixin的ES7.除非使用React生命周期的方法,否则将可重用代码与React耦合是没有意义的.
小智 1
您可以使用 modulejs。或者你可以使用 mixins ( https://facebook.github.io/react/docs/reusable-components.html#mixins )
mixin 示例: 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'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22248 次 |
| 最近记录: |