如何通过道具改变私人@ mobx.observable.ref mobx状态?

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

目前我的课程是这样定义的:

type ClapWidgetProps = {
  animate: boolean,

};

export class Widget extends React.Component<WidgetProps> {
  @mobx.observable.ref private animate: boolean = this.props.animate || false;

这个可观察的animate控制小部件内的一些动画效果。

正如你所看到的,内部状态animatethis.props.animate初始化。

我想要实现的是,我希望能够在初始化之后通过animate连续改变可观察的this.props.animate的值。

当房产改变时,我如何让this.props.animate覆盖可观察的animate

typescript mobx
2个回答
1
投票

如果您需要从内部和外部组件控制动画,您需要从React生命周期方法中受益

@observer
export class Widget extends React.Component<WidgetProps> {
  @observable private animate: boolean = this.props.animate || false;

  toggleAnimate = () => {
    this.animate = !this.animate;
  }

  componentDidUpdate(prevProps) {
    if (prevProps.animate !== this.props.animate) {
      this.animate = this.props.animate;
    }
  }

  render() {
     // call  this.toggleAnimate to change animate from inside component
  }
}

而来自外部

// some jsx

<Widget animate={this.state.animate} />

// and if outer component this.state.animate changes - it will cause a change of Widget animate prop


1
投票

MobX是关于stores的,它是您的应用程序的状态。在你的例子中,你有2个动画属性的来源(在你的Widget组件中以及你传递给Widget之外的某个地方,如prop)并不是一个好习惯。

这将是设置应用程序的更好方法

class Store {
    @observable animate = false;

    @action
    setAnimate(animate) {
        this.animate = animate;
    }
}

@inject('store')
class Widget extends React.Component {
    toggleAnimate = () => {
        const { store } = this.props;
        store.setAnimate(!store.animate);
    }

    render() {
        const { animate } = this.props.store;
        // whenever animate changes in your store render method will trigger
    }
}

请注意,这不是一个有用的示例,因为您必须在应用程序的根级别设置Provider。有关更多信息,请参阅Provider and inject https://github.com/mobxjs/mobx-react部分。

您可以在https://mobx.js.org/best/store.html找到更多关于定义商店的信息。

© www.soinside.com 2019 - 2024. All rights reserved.