菜鸟教程小白 发表于 2022-12-11 19:41:20

javascript - 多个 React-Native 组件的可重用动画


                                            <p><p>我正在尝试为一系列组件创建默认的 offsetY 动画。这些组件从不同的外部文件加载到 App.js 中。目前我在每个组件中使用以下动画设置,但我想找到一种 DRY(不要重复自己)的方式来实现它。如何只设置一个动画并避免这种重复?动画需要在 App.js 中声明还是我也可以在外部文件中创建?</p>

<p>谁能指出我正确的方向?提前谢谢!</p>

<p>组件设置</p>

<pre><code>import React, { Component } from &#39;react&#39;;
import {
Animated,
View,
Text,
StyleSheet,
DeviceEventEmitter
} from &#39;react-native&#39;;

// Custom **********************************************************************
import styles from &#39;../styles&#39;

export class BlueberryComp extends Component {
constructor(props) {
    super(props)
    this.state = {
      offsetY: new Animated.Value(0),
      fadeIn: new Animated.Value(0)
    }
}

componentDidMount() {
    Animated.parallel([
      Animated.timing(
      this.state.offsetY,
      {
          toValue: -100,
          duration: 1000,
      }),
      Animated.timing(
      this.state.fadeIn,
      {
          toValue: 1,
          duration: 1000,
      }
      )
    ]).start();
}


render() {
    let { offsetY, fadeIn } = this.state;

    return (
      &lt;Animated.View style={{ opacity: fadeIn, transform: [{ translateY: offsetY }] }}&gt;
      &lt;Text style={styles.h1}&gt;{this.props.name}&lt;/Text&gt;
      &lt;/Animated.View&gt;
    );
}
}
</code></pre>

<p>App.js,这里我使用 renderIf 将每个组件加载到渲染 View 中。</p>

<pre><code>render() {
    const { isIce, isMint, isBlueberry } = this.state
    return (
      &lt;View style={styles.container}&gt;
            {renderIf(isIce, &lt;IceComp name={this.state.name} /&gt;)}
            {renderIf(isMint, &lt;MintComp name={this.state.name} /&gt;)}
            {renderIf(isBlueberry, &lt;BlueberryComp name={this.state.name} /&gt;)}
      &lt;/View&gt;
    )
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>所以,在多次尝试和失败之后,我从 Gosha Arinich 那里找到了这个很好的例子。我希望这将帮助 future 的用户解决我遇到的同样问题。不过,谢谢@Cruiser。</p>

<p>React Native 中的动画外观和消失
<a href="https://goshakkk.name/react-native-animated-appearance-disappearance/" rel="noreferrer noopener nofollow">https://goshakkk.name/react-native-animated-appearance-disappearance/</a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于javascript - 多个 React-Native 组件的可重用动画,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48523969/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48523969/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: javascript - 多个 React-Native 组件的可重用动画