美文网首页
React Native setNativeProps使用

React Native setNativeProps使用

作者: 冷洪林 | 来源:发表于2017-01-10 10:25 被阅读193次

有时候我们需要直接改动组件并触发局部的刷新,但不使用state或是propssetNativeProps 方法可以理解为web的直接修改dom。使用该方法修改 ViewText 等 RN自带的组件 ,则不会触发组件的 componentWillReceivePropsshouldComponentUpdatecomponentWillUpdate 等组件生命周期中的方法。

使用例子

  class MyButton extends React.Component({
    setNativeProps(nativeProps) {
         this._root.setNativeProps({   //这里输入你要修改的组件style
            height:48,
            backgroundColor:'red'
         });
    },
    render() {
         return (
            <View ref={component => this._root = component} {...this.props} style={styles.button}>
             <Text>{this.props.label}</Text>
        </View>
         )
    },
  });

避免和render方法的冲突

如果要更新一个由render方法来维护的属性,则可能会碰到一些出人意料的bug。因为每一次组件重新渲染都可能引起属性变化,这样一来,之前通过setNativeProps所设定的值就被完全忽略和覆盖掉了。

相关文章

网友评论

      本文标题:React Native setNativeProps使用

      本文链接:https://www.haomeiwen.com/subject/iljkbttx.html