reactjs – 将React类函数存储在单独的文件中
发布时间:2020-12-15 16:18:42 所属栏目:百科 来源:网络整理
导读:有没有办法将react类的函数存储在一个单独的文件中,然后导入这些函数以供使用?想要这样做的原因纯粹是为了减少组件的大小并按类别对功能进行分组. 例如: import functionIWantToImport from '../functions/functionIWantToImport';import anotherFunction
有没有办法将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; } 我知道我可以使用不属于组件类的辅助函数来完成此操作.但我想用我的组件功能来节省空间,并清理我的代码. 解决方法
使用标准的JS函数(不是箭头函数),并将函数绑定到构造函数中的实例:
function externalMethod() { // simulates imported function return this.state.example; } class Test extends React.Component { constructor(props){ super(props); this.state = { example: 'example' }; this.externalMethod = externalMethod.bind(this); } render() { return ( <div>{ this.externalMethod() }</div> ); } } ReactDOM.render( <Test />,test ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="test"></div> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |