【问题标题】:Storing React Class functions in separate files将 React 类函数存储在单独的文件中
【发布时间】: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


【解决方案1】:

使用标准 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>

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多