这可能是一个关于如何处理外部函数的导入和导出函数的相当普遍的问题。
所以我有一个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
函数会很简洁,并且会节省我很多多余的打字。提前致谢!
可以像这样一次导入多个方法:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)