ReactJS-重构后无法获得从单独文件加载值的功能

时间:2018-07-04 23:03:00

标签: javascript reactjs import

尝试将React中App类中的功能分解为单独的文件后,我正在处理大量导入/导出问题,并且想知道是否可以得到一些建议:

首先,将其他文件/类中的类中的函数分解出来是否合乎逻辑?

第二,这是我遇到的一个具体问题:

预期的行为:函数MainTable.tableGen()应该返回App的render()可以处理的值。

实际行为::单步调试器显示tableGen()未被触发,但可以识别。换句话说,它不是在运行函数并返回值,而是在打印时返回函数。

Main.js:

import MainTable from './app/components/input_table/maintable';

export default class App extends React.Component {
    constructor(props){
      this.MainTable = this.MainTable.bind(this);
}

MainTable(){
MainTable.tableGen();  //Call the function that's in the external file here
}
render(){
        return (
          <div>
          <table>
          <tbody onLoad = {this.broadcast()}>  
            {this.MainTable}  //The MainTable.tableGen() function populates the table using a series of loops 
          </tbody>
          </table>
          <ButtonMenu onRow = {this.onRowButton} onCol = {this.onColumnButton} undo ={this.onUndoAction} redo = {this.onRedoAction} reset = {this.onResetAction} />
          </div>

        );
      }

}

maintable.js:

class baseTable extends React.Component{
  constructor(props){
    //properties
    super(props);
  }

 tableGen(){


... function code here...

}
const MainTable = new baseTable; 

export default MainTable;

1 个答案:

答案 0 :(得分:1)

确保您的tableGen()返回JSX,不带引号。

return <h3>Hello World</h3>;

然后,您的MainTable函数应具有return关键字:

MainTable() {
  return MainTable.tableGen();
}

然后,在JSX中引用该函数时调用该函数:

{this.MainTable()}