Processing external function imports

This can be a pretty general question on how to handle importing external functions and exporting functions.

So I have 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);

Here's what my external functions look like (they are not part component, just files with functions that will be reused in various components):

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

Now it works fine, but it is sickening. My files grow in size, and it’s always a pain of bindthese functions. I get the need to import functions / components, but do I really need bindthem that way? Something like functions arrowwould be neat and save me from typing too much. Thanks in advance!

+4
source share
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);
+2

, 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>; }
}   
+1

Source: https://habr.com/ru/post/1686346/


All Articles