为什么当我对 render 方法使用 fat arrow 时 reactjs/mobx 代码没有重新呈现?
Why the reactjs/mobx code does not rerender when I use fat arrow for the render method?
这是我的代码:
import React, {Component} from 'react';
import * as mobx from 'mobx';
import * as mobxReact from 'mobx-react';
import classNames from 'classnames';
import './CssClassApp.css';
@mobxReact.observer
export class CssClassApp extends Component {
@mobx.observable.ref clapping: boolean = false;
@mobx.action.bound
startAnimate() {
this.animating = true;
setTimeout(() => this.stopAnimate(), 2000);
};
@mobx.action.bound
stopAnimate() {
console.log(`Stopping animation`)
this.animating = false;
};
render() {
return (
<div>
<input
className="button"
type="button"
value="Test"
onClick={this.startAnimate}
/>
<div style={{transition: `border 1500ms ease-out`}}
className={classNames('normal',
{'on': this.animating})}>
Testing timeout
</div>
</div>
);
}
}
及相关css
.on {
border: 5px solid red;
}
.normal {
height: 100px;
widows: 100px;
}
它工作正常。
但是如果我将 render
方法更改为 render = () =>
边框根本不会淡入。
为什么?是什么导致此错误:react
、mobx
或 typescript
?
使用 render = () => {}
您在 {'on': this.animating})}>
中的 this
不再绑定到同一范围!因此,您的 UI 表现不同。
您必须了解如何根据您的需要正确绑定this
。或者您只保留语法原样,因为根本不需要更改方法的语法。
这可能是一个很好的信息来源:
这是我的代码:
import React, {Component} from 'react';
import * as mobx from 'mobx';
import * as mobxReact from 'mobx-react';
import classNames from 'classnames';
import './CssClassApp.css';
@mobxReact.observer
export class CssClassApp extends Component {
@mobx.observable.ref clapping: boolean = false;
@mobx.action.bound
startAnimate() {
this.animating = true;
setTimeout(() => this.stopAnimate(), 2000);
};
@mobx.action.bound
stopAnimate() {
console.log(`Stopping animation`)
this.animating = false;
};
render() {
return (
<div>
<input
className="button"
type="button"
value="Test"
onClick={this.startAnimate}
/>
<div style={{transition: `border 1500ms ease-out`}}
className={classNames('normal',
{'on': this.animating})}>
Testing timeout
</div>
</div>
);
}
}
及相关css
.on {
border: 5px solid red;
}
.normal {
height: 100px;
widows: 100px;
}
它工作正常。
但是如果我将 render
方法更改为 render = () =>
边框根本不会淡入。
为什么?是什么导致此错误:react
、mobx
或 typescript
?
使用 render = () => {}
您在 {'on': this.animating})}>
中的 this
不再绑定到同一范围!因此,您的 UI 表现不同。
您必须了解如何根据您的需要正确绑定this
。或者您只保留语法原样,因为根本不需要更改方法的语法。
这可能是一个很好的信息来源: