处理外部函数导入 [英] Handling external function imports

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

问题描述

关于如何处理外部函数的导入和导出函数,这可能是一个相当笼统的问题.

This might be a rather general question on how to handle imports of external functions and exporting functions.

所以我有这样的component:

import React, {Component} from "react";
import {handleChange} from "./path";
//imports from different files...

class Foo extends Component {
    constructor(props) {
        super(props);

        this.bindFunctions();

        this.state = {...};
    };

    //Arrow functions to bind them
    alreadyBound = () => {};

    render() {
        return (
            <div>
                Some text
            </div>
        );
    }

    bindFunctions = () => {
        this.handleChange = handleChange.bind(this);
        //dozens of functions to follow...
    }
}

export default compose(
    translate('translations'),
    connect()
)(Foo);

这是我的外部函数的样子(它们不是component的一部分,只是具有可以在各种components中重用的函数的文件):

This is how my external functions look like (They are not part of a component, just files with functions to be reused in various components):

export function handleChange(value, {target: {name, type}}) {
    this.setState({[name]: value});
}

现在,这可以正常工作,但令人作呕.我的文件越来越大,总是bind这些功能很痛苦.我有必要导入功能/组件,但是我真的必须以这种方式bind导入它们吗?诸如arrow函数之类的东西会很整洁,可以为我节省很多多余的键入操作.预先感谢!

Now this works perfectly fine but it's nauseating. My files grow in size and it's a pain to always bind those functions. I get the necessity of importing the functions/components, but do I really have to bind them in this fashion? Something like arrow functions would be neat and would save me lot of redundant typing. Thanks in advance!

推荐答案

一个人可以一次导入多个方法,如下所示:

One could import multiple methods at once like this:

import * as path from  "./path";

class Foo { }

然后我们可以将它们分配为静态方法:

Then we can assign them as static methods:

Object.assign( Foo, path );

或作为原型方法:

Object.assign( Foo.prototype, path );

如果要绑定上下文,则要困难一些.这可以在构造函数中完成:

If you want to bind the context its a bit more difficult. That could be done in the constructor:

import * as path from  "./path";

class Foo { 
  constructor(){
    for(var key in path) this[key] = path[key].bind(this);
  }
  //...
}

或者如果您只想绑定一些功能(也许更快):

Or if you just want a few functions to be bound ( maybe faster ) :

import * as path from  "./path";

class Foo { 
  constructor(){
    const bind = ["onClick","onResize" /* whatever*/];
    for(var key of bind) this[key] = this[key].bind(this);
  }
}

Object.assign(Foo, path.prototype);

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

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