我有一个自定义模式,它在componentDidMount时滑入:

componentDidMount() {

    Animated.timing(this._animatedValue.y, {
        duration: 200,
        toValue: 0
    }).start()

} 

好吧,这很简单.然而,我也喜欢在组件卸载时滑出模式.对我来说,componentWillUnmount()应该是正确的,因为它是一种优雅的陈述方式:

componentWillUnmount() {

    Animated.timing(this._animatedValue.y, {
        duration: 200,
        toValue: deviceHeight
    }).start()

} 

但这当然有not种效果,因为React不会等到我完成动画.

现在我用一个自定义函数来解决这个问题:

closeModal() {


    Animated.timing(this._animatedValue.y, {
        duration: C.filterModalDuration,
        toValue: deviceHeight
    }).start()

   InteractionManager.runAfterInteractions(() => {
     this.props.UnmountThisComponent()
   })

}

这当然不是那么优雅,但它很管用.然而,如果我需要从组件树中较低的组件调用此函数,那么痛苦就开始了,也就是说,我需要通过onUnmount={()=> closeModal()}手动传递此函数,然后通过onUnmount={this.props.onUnmount}反复传递...

然后我想我可以用redux&redux connect.我想从子组件触发redux状态更改,然后通过componentWillRecieveProps()调用函数,如下所示:

componentWillReceiveProps (nextProps) {

  if (nextProps.closeFilter === true) {
          this.closeModal()
  }

}

然而,这让人感觉非常刻薄和迫切.

Is there any way to solve this problem in an elegant / declarative way?

推荐答案

我不会在动画完成后使用InteractionManager.runAfterInteractions执行.我建议使用start回调.

Animated.timing(this.animatedValue, {}).start(() => this.props.closeModal())

有一些东西,比如https://github.com/mosesoak/react-native-conductor,可以帮助你协调深层动画和 firebase 备份.这充分利用了context的优势.

你也可以使用redux,就像你try 过的那样,但是我会使用componentDidUpdate而不是componentWillReceiveProps.

只有在componentWillReceiveProps中才是安全的原因.

如果触发componentWillReceiveProps中的dispatch,则会导致其他组件中的setState导致应用程序中断.

Overall: I would recommend this flow. (Close Action Initiated) => Animate Modal Closed => in start(() => {}) callback cause a setState or set a piece of data in your redux store that will then unmount your modal which is now hidden.

这样就可以获得卸载动画.

如果您使用的是react-navigation这样的路由,我建议设置mode: "modal"导航样式.这样,卸载/安装模态动画就可以为您提供服务.

React-native相关问答推荐

NPM INSTALL 在 react-native 项目上失败:无法解析 react 和 react-dom 的依赖树

react-native-snap-carousel 无法正确渲染

React native flexbox - 如何做 percentages || columns || responsive || grid etc

Eslint 错误,configuration for rule "import/no-cycle" is invalid

图像背景ResizeMode调整大小模式

使用 .env 变量在 react-native 应用程序上设置 appcenter

为了回调 URL 的目的,在 Expo 中运行的 React Native 元素的 info.plist 在哪里?

Soundcloud API /stream 端点给出 401 错误

无法访问函数内部的状态

如何以编程方式在 react-native 中截屏

如何在 array.map 中的每个元素之后添加逗号,除了 React JSX 中的最后一个元素

如何使 React Native Animated.View 可点击?

react-native Http 拦截器

Unexpected token on "export default const"

react-navigation模式高度

Expo LAN 配置不适用于新的 ReactNative 元素

使用 React Native 一次启动多个 Animated.timing

React Native Build Error on IOS - typedef 用不同类型重新定义('uint8_t'(又名'unsigned char')与'enum clockid_t')

如何在 React Native 中从底部滑入和滑出

如何将 jest 测试移动到 /test 文件夹并让它们运行?