当前位置:   article > 正文

setNativeProps详解_rn setnativeprops

rn setnativeprops

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

比如header渐变和搜索框出现都是直接通过setNativeProps来实现的。因为header要响应滚动事件,如果使用setState来实现的话,那么render会被频繁触发,动画会比较卡顿,所以这种情况下,setNativeProps就能排上用场。

实现图中的效果很简单,但是冗余代码比较多,所以就不拿来做示例了。下面的代码实现了一个Button组件。点击的时候改变背景色,这就是setNativeProps最常见的使用方式了。

  1. class Button extends Component {
  2. render() {
  3. return (
  4. <View ref={(c) => this._refButton = c} style={buttonStyles.button}
  5. onTouchStart={(e) => this._onTouchStart(e)}
  6. onTouchEnd={(e) => this._onTouchEnd(e)}
  7. >
  8. <Text style={buttonStyles.text}>{this.props.children}</Text>
  9. </View>
  10. );
  11. }
  12. _onTouchStart(e) {
  13. /**
  14. * 这里直接操作style以达到效果
  15. * @type {Object}
  16. */
  17. this._refButton.setNativeProps({
  18. style: {backgroundColor: '#666'}
  19. });
  20. }
  21. _onTouchEnd() {
  22. this._refButton.setNativeProps({
  23. style: {backgroundColor: '#999'}
  24. });
  25. }
  26. }

那么我们究竟需要在何种情况下使用直接操作?在RN文档中这样描述的:


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


可以看出setNativeProps有时候非常好使,对于用惯了JQ的人来说简直就是福音。但是我并没有在官方文档找到那些属性可以用setNativeProps来操作,大家只是猜猜,嗯,style属性应该可以,于是乎就用起来了。下面是我整理出来的可以直接操作的属性列表

 

View

  • pointerEvents
  • accessible
  • accessibilityLabel
  • accessibilityComponentType
  • accessibilityLiveRegion
  • accessibilityTraits
  • importantForAccessibility
  • testID
  • renderToHardwareTextureAndroid
  • shouldRasterizeIOS
  • onLayout
  • onAccessibilityTap
  • onMagicTap
  • collapsable
  • needsOffscreenAlphaCompositing
  • style

Text

除了包含上面View的所有属性外还包括:

  • isHighlighted
  • numberOfLines
  • ellipsizeMode
  • allowFontScaling
  • selectable
  • adjustsFontSizeToFit
  • minimumFontScale

Image

包含View所有支持的属性,Android和IOS略有不同Android平台下,Image组件有children的时候和IOS支持的属性列表一样,如果Image没有children,那么它还包含如下属性:

  • src
  • defaultSource
  • loadingIndicatorSrc
  • resizeMode
  • progressiveRenderingEnabled
  • fadeDuration
  • shouldNotifyLoadEvents

使用setNativeProps需要注意的几点:

  首先 setNativeProps只能用在RN的核心组件(被native支持)上,不能用在混合组件上。

对于受控的TextInput,当bufferDelay设置比较小而且用户输入比较快的时候,可能会丢失字符,所以一些开发者干脆直接使用setNativeProps来设置TextInput的值。如下:

  1. export default class App extends React.Component {
  2. clearText = () => {
  3. this._textInput.setNativeProps({text: ''});
  4. }
  5. render() {
  6. return (
  7. <View style={{flex: 1}}>
  8. <TextInput
  9. ref={component => this._textInput = component}
  10. style={{height: 50, flex: 1, marginHorizontal: 20, borderWidth: 1, borderColor: '#ccc'}}
  11. />
  12. <TouchableOpacity onPress={this.clearText}>
  13. <Text>Clear text</Text>
  14. </TouchableOpacity>
  15. </View>
  16. );
  17. }
  18. }

这里需要注意的是原生方法仅仅改变了原生组件上的值,RN中的state并没有发生变化,也不会触发这个TextInput上的onChange事件。

其实上面这些东西都是在RN源码里面能找到的,你要是不确定某个属性能否通过setNativeProps设置的话,可以去对应组件的源码里面查看,它被封装在组件的viewConfig属性里面,所以node_module/react-native/Libraries/Image/Image.ios.js里面有这样的代码

  1. const Image = React.createClass({
  2. /**
  3. * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
  4. * make `this` look like an actual native component class.
  5. */
  6. viewConfig: {
  7. uiViewClassName: 'UIView',
  8. validAttributes: ReactNativeViewAttributes.UIView
  9. },
  10. ...
  11. render: function() {
  12. ...
  13. return (
  14. <RCTImageView
  15. {...this.props}
  16. style={style}
  17. resizeMode={resizeMode}
  18. tintColor={tintColor}
  19. source={sources}
  20. />
  21. );
  22. }
  23. });

可以看出Image组件并没有把比较重要的prop source  没有被纳入到可被直接修改的列表中。在IOS平台上,RN暴露给我们的Image是一个复合组件,原生的RCTImageView所接收的source需要一个数组,而封装过的Image需要的是一个Object,使用setNativeProps会有点奇怪吧。还有在Android平台,RKImage和RCTTextInlineImage需要的是src属性,也是一个数组。如果你非要使用setNativeProps来改变Image的source,可以像下面这样集成Image

  1. class MyImage extends Image {
  2. viewConfig = Object.assign({} , this.viewConfig, {
  3. validAttributes: Object.assign(
  4. {},
  5. this.viewConfig.validAttributes,
  6. {[Platform.OS === 'ios' ? 'source' : 'src']: true})
  7. });
  8. constructor() {
  9. super();
  10. this.setNativeProps = (props = {}) => {
  11. if (props.source) {
  12. const source = resolveAssetSource(props.source);
  13. let sourceAttr = Platform.OS === 'ios' ? 'source' : 'src';
  14. let sources;
  15. if (Array.isArray(source)) {
  16. sources = source;
  17. } else {
  18. sources = [source];
  19. }
  20. Object.assign(props, {[sourceAttr]: sources});
  21. }
  22. return super.setNativeProps(props);
  23. }
  24. }
  25. }
  26. // 实现
  27. class TestDemo extends Component {
  28. // 设置source
  29. _setSource() {
  30. this._refImg.setNativeProps({
  31. source: {uri: 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2478206899,4000352250&fm=80&w=179&h=119&img.JPEG'}
  32. });
  33. }
  34. render() {
  35. return(
  36. <MyImage
  37. ref={(c) => this._refImg = c}
  38. style={styles.box}
  39. source={{uri: 'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=3497889018,3008123053&fm=80&w=179&h=119&img.JPEG'}} />
  40. )
  41. }
  42. }

但是,但是,但是上面的代码只是为了探讨一种方案,以及研究在RN里面setNativeProps是如何工作的,我们是不可能真正的在项目中使用的,仅仅是学习之用。既然都继承了一个新的类,为什么不自定义一个组件来实现想要的功能呢,用setState多方便。

对于setNativeProps和react推崇的思想之间的矛盾,我觉得他们是可以共存的。对于不同的业务、技术、场景,选择合适的就是最好的

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/134260
推荐阅读