处理外部函数导入

时间:2017-09-25 13:57:37

标签: javascript reactjs ecmascript-6

这可能是关于如何处理外部函数导入和导出函数的一个相当普遍的问题。

所以我有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中重用的函数的文件):

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

现在这种方法非常好,但令人作呕。我的文件大小增加,总是bind这些函数很难。我有必要导入函数/组件,但我真的必须以这种方式bind吗?像arrow函数这样的东西会很整洁,可以节省很多冗余的输入。提前谢谢!

2 个答案:

答案 0 :(得分:2)

可以像这样一次导入多个方法:

import * as path from  "./path";

class Foo { }

然后我们可以将它们指定为静态方法:

Object.assign( Foo, path );

或作为原型方法:

Object.assign( Foo.prototype, path );

如果你想绑定上下文有点困难。这可以在构造函数中完成:

import * as path from  "./path";

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

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

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

答案 1 :(得分:1)

作为替代设计,您可以考虑使用mixin,例如:

let clickable = (superclass) => class extends superclass {  

    constructor(props) { super(props); };

    handleClick = () => { console.log( "clicked ", this ); };
};

class Foo extends clickable(Component) {
    constructor(props) { super(props); this.state = { ... };};

    render() { return <div onClick={this.handleClick}>foobar</div>; }
}   
相关问题