React Native ref高級用法&&setNativeProps使用


ref屬性不只是string 
ref屬性不僅接受string類型的參數,而且它還接受一個function作為

callback。這一特性讓開發者對ref的使用更加靈活。
render() {
    return <TextInput ref={(c) => this._input = c} />;
  },
  componentDidMount() {
    this._input.focus();
  },
render(){
    return <View ref={ (e) => this._view = e } />//將組件view作為參數賦值給了this._view
}
componentDidMount(){
    this._view.style = { backgroundColor:'red',width:100,height:200 }
}

 

需要提醒大家的是,只有在組件的render方法被調用時,ref才會被調用,組件才會返回ref。如果你在調用this.refs.xx時render方法還沒被調用,那么你得到的是undefined。 
心得:ref屬性在開發中使用頻率很高,使用它你可以獲取到任何你想要獲取的組件的對象,有個這個對象你就可以靈活地做很多事情,比如:讀寫對象的變量,甚至調用對象的函數。

讓組件做到局部刷新setNativeProps 
有時候我們需要直接改動組件並觸發局部的刷新,但不使用state或是props。 
setNativeProps 方法可以理解為web的直接修改dom。使用該方法修改 View 、 Text 等 RN自帶的組件 ,則不會觸發組件的 componentWillReceiveProps 、 shouldComponentUpdate 、componentWillUpdate 等組件生命周期中的方法。

import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  TextInput
} from 'react-native';

class AwesomeProject extends Component {
    // 構造
    constructor(props) {
      super(props);
      // 初始狀態
      this.state = {
        textInputValue: ''
      };
      this.buttonPressed = this.buttonPressed.bind(this);
    }

    buttonPressed() { //當按鈕按下的時候執行此函數
      let textInputValue = 'new value';

      this.setState({textInputValue});

      //修改文本輸入框的屬性值
      this.refs.textInputRefer.setNativeProps({
        editable:false
      });

      this.refs.text2.setNativeProps({
        style:{
          color:'blue',
          fontSize:30
        }
      });
        //使文本輸入框變為不可編輯
    }

    render() {
      return (
          //ref={'text2'}>   //指定本組件的引用名
          <View style={styles.container}>
              <Text style={styles.buttonStyle} onPress={this.buttonPressed}>
                  按我
              </Text>
              <Text style={styles.textPromptStyle} ref="text2">
                  文字提示
              </Text>
            <View>
              <TextInput style={styles.textInputStyle}
                ref="textInputRefer"
                value={this.state.textInputValue}
                onChangeText={(textInputValue)=>this.setState({textInputValue})}
              />
            </View>
        </View>
      );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    buttonStyle: { //文本組件樣式,定義簡單的按鈕
        fontSize: 20,
        backgroundColor: 'grey'
    },
    textPromptStyle: { //文本組件樣式
        fontSize: 20
    },
    textInputStyle: { //文本輸入組件樣式
        width: 150,
        height: 50,
        fontSize: 20,
        backgroundColor: 'grey'
    }
});


AppRegistry.registerComponent('Redux', () => AwesomeProject);


當點擊按鈕時,會刷新3個控件的值,但是只是單獨去改變,而不是通過改變state狀態機的機制來刷新界面,在重復需要多次刷新時使用,普通的時候直接通過state改變即可。 

這樣用的缺點就是局部改變,回導致狀態機混亂。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM