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

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

我尝试过:

内部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"

谢谢您的帮助。

freewindwl 回答:如何在ReactJS的导出函数中使用this.state

this.errorHandler = errorHandler.bind(this);

因为您刚刚导出了函数,所以它还不属于您的课程

,

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

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

<input 
 {...props}
 onClick={e => this.errorHandler()} // call method
/>
本文链接:https://www.f2er.com/3138425.html

大家都在问