如何在ReactJS的导出函数中使用this.state

问题描述 投票:0回答:2

我正在尝试从App组件内部的导出函数中使用this.state。绑定方法不起作用。有什么想法吗?

我尝试过:

inside error-handler.js

    export function errorHandler() {
    console.log(this.state);
}

内部App.js

   ...

   import { errorHandler } from '../../helpers/error-handler';

   class App extends React.Component {
   constructor(props) {
       super(props);
       this.errorHandler = errorHandler.bind(this);
   }

   ...

尝试在App.js中运行errorHandler()时的结果:

"Cannot read property 'bind' of undefined"

谢谢您的帮助。

javascript reactjs export state bind
2个回答
1
投票
this.errorHandler = errorHandler.bind(this);

因为您刚刚导出函数,所以它还不是您的类的一部分


1
投票

errorHandler只是一个导出函数。因此,您必须绑定以下方法。

constructor(props) {
    super(props);
    this.errorHandler = errorHandler.bind(this); // bind event
}
...
...

<input 
 {...props}
 onClick={e => this.errorHandler()} // call method
/>
© www.soinside.com 2019 - 2024. All rights reserved.