【发布时间】:2018-04-26 16:28:09
【问题描述】:
有没有办法将 React 类的函数存储在单独的文件中,然后导入这些函数以供使用?想要这样做的原因纯粹是为了减少我的组件的大小并按类别对功能进行分组。
例如:
import functionIWantToImport from '../functions/functionIWantToImport';
import anotherFunction from '../functions/anotherFunction';
Class Test extends React.Component {
constructor(props){
super(props);
this.state = {};
}
//and then include the functions like below:
functionIWantToImport;
anotherFunction;
}
我知道我可以使用不属于组件类的辅助函数来做到这一点。但我想用我的组件函数来做这件事,以节省空间,并清理我的代码。
【问题讨论】:
-
当然可以,您只需要确保以不会产生错误的方式保留变量的范围和上下文以及
this。例如,外部箭头函数将具有与class不同的this上下文。您尝试过是否遇到了一些问题?
标签: reactjs class import components code-cleanup