reactjs - React-native:将动画值保留在状态中还是作为类属性?

标签 reactjs react-native ecmascript-6

将动画值 (fadeAnim) 作为状态属性更好还是将其放入类属性中更好?

示例:

class ModalShade extends React.Component {
    fadeAnim = new Animated.Value(0)

    render() {
        return (
            <Animated.View
                cls="bg-black absolute-fill"
                style={{ opacity: this.fadeAnim }}
            />
        )
    }

    componentDidMount() {
        Animated.spring(
            this.fadeAnim, {
                toValue: 0.6,
                tension: 100,
                friction: 20
            }
        ).start();
    }
}

澄清: 我知道状态用于 react 的协调。 React-native 的 Animated 值会绕过通常的 render(),因此即使没有状态更改,组件也会更新。

我认为在 shouldComponentUpdate 中比较 Animated.Value 没有任何意义,这就是我将其移出状态的原因。

最佳答案

最好遵循官方文档并使用国家属性(property)。 有两个很好的理由:

  1. 您希望将所有对组件渲染结果有影响的内容保留在状态/属性/上下文中。
  2. React-Native Animated 库有自己的优化,可以避免 setState 调用并在动画组件发生变化时重新渲染。这是官方文档的引用

When the component mounts, the opacity is set to 0. Then, an easing animation is started on the fadeAnim animated value, which will update all of its dependent mappings (in this case, just the opacity) on each frame as the value animates to the final value of 1.

This is done in an optimized way that is faster than calling setState and re-rendering.

关于reactjs - React-native:将动画值保留在状态中还是作为类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40436481/

相关文章:

javascript - 有没有办法将 onClick 事件添加到自定义组件

reactjs - 获取输入组件的 onBlur 属性

javascript - 警告 : validateDOMNesting(…): <form> cannot appear as a descendant of <form> by using semantic-ui-react modal

node.js - npm启动时react-native报错

javascript - 在 ReactNative 中使用 slider 滚动水平 ScrollView

javascript - ReactJS - child 如何访问它是 parent 的 Prop ?

javascript - axios http 总是返回空数据

javascript - 在 React Native 中授予权限

javascript - JS 范围内的导出

javascript - 如何根据属性键对值进行唯一和求和