RN知识

RN-setNativeProps、LayoutAnimatio

2017-04-25  本文已影响81人  精神病患者link常

在React-Native里面,如果要改变组件的样式可以通过state 或者 props来做到。但有些时候由于性能瓶颈,不得不放弃通过触发render的方式来改样式,而是通过setNativeProps 来直接更改原生组件的样式属性 来达到相同的效果

setNativeProps可直接改变属性而不调用render方法

使用条件:

在(不得不)频繁刷新而又遇到了性能瓶颈的时候,直接操作组件并不是应该经常使用的工具。一般来说只是用来创建连续的动画,同时避免渲染组件结构和同步太多视图变化所带来的大量开销。setNativeProps是一个“简单粗暴”的方法,它直接在底层(DOM、UIView等)而不是React组件中记录state,这样会使代码逻辑难以理清。所以在使用这个方法之前,请尽量先尝试用setStateshouldComponentUpdate方法来解决问题。

例:用setNativeProps来改变style(背景色和高度)

_onTouchStart(){
   this._refButton.setNativeProps({
       style:{backgroundColor:'blue',height:300}
   })
}
_onTouchEnd(){
   this._refButton.setNativeProps({
       style:{backgroundColor:'red',height:200}
   })
}
render() {
        return (
            <View ref={(c) => this._refButton = c}
                  style={styles.container}
                  onTouchStart={(e) => this._onTouchStart(e)}
                  onTouchEnd={(e) => this._onTouchEnd(e)}>
                    <Text> 点击测试 setNativeProps </Text>
            </View>
        );
}
const styles = StyleSheet.create({
    container: {
        //flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'red',
        height:200,
    },
QQ20170425-183139.gif

so 问题来了 很生硬的有木有,能不能加点过渡效果啊

Of course

这就用到了LayoutAnimation,可以和iOS原生的媲美,666

 // Enable LayoutAnimation under Android
 if (Platform.OS === 'android') {
      UIManager.setLayoutAnimationEnabledExperimental(true)
 }
 componentWillUpdate() {
       console.log('componentWillUpdate...');
       LayoutAnimation.easeInEaseOut();
       LayoutAnimation.linear();
       LayoutAnimation.spring();

        //或
       LayoutAnimation.configureNext(CustomLayoutAnimation);
 }
var CustomLayoutAnimation = {
    duration: 10,
    create: {
        type: LayoutAnimation.Types.linear,
        property: LayoutAnimation.Properties.opacity,
    },
    update: {
        type: LayoutAnimation.Types.easeInEaseOut,
    },
    delete:{
        type: LayoutAnimation.Types.linear,
        property: LayoutAnimation.Properties.opacity,
    }
};

以上是LayoutAnimation的介绍及声明

我们只需要在需要的地方加上

LayoutAnimation.configureNext(CustomLayoutAnimation

这一句即可

_onTouchStart(){
   this._refButton.setNativeProps({
       style:{backgroundColor:'blue',height:300}
   });
   LayoutAnimation.configureNext(CustomLayoutAnimation);
}
_onTouchEnd(){
   this._refButton.setNativeProps({
       style:{backgroundColor:'red',height:200}
   });
   LayoutAnimation.configureNext(CustomLayoutAnimation);
}
QQ20170425-185047.gif
上一篇 下一篇

猜你喜欢

热点阅读