2017-10-05 52 views
1

我在我的應用程序中使用陣營,導航和應用程序組成StackNavigator與多個屏幕,某些屏幕,其中具有的TextInput與autoFocus={true}如何在React-Native中獲得鍵盤的高度?

問題:在這些屏幕上,當組件呈現,屏幕的高度正在構造函數中設置:

constructor(props) { 
    super(props); 
    this.state = { 
     height: Dimensions.get('window').height, 
    }; 
} 

但是,因爲的TextInput的autoFocustrue,在屏幕上這個畫面彈出,鍵盤幾乎立即後呈現,造成水泥沙漿新界東北堆填區重新渲染由於被添加到鍵盤中componentWillMount的事件監聽:

componentWillMount() { 
    this.keyboardWillShowListener = Keyboard.addListener(
         'keyboardWillShow', this.keyboardWillShow.bind(this)); 
} 

keyboardWillShow(e) { 
    this.setState({ height: Dimensions.get('window').height * 0.9 - e.endCoordinates.height }); 
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); 
} 

這會影響性能,我想,以避免不必要的重新呈現。

問題:
1.是否可以設置鍵盤的陣營,導航的ScreenProps動態高度(具體取決於設備)?
2.是否可以用React-Navigation的state.params做同樣的事情?
3.除了應用KeyboardAvoidingView或this module之外,還有其他方法可以解決這個問題嗎?

回答

5

這是我做過什麼:

如果應用 「授權/註冊/登錄屏幕」,則:

  1. 在componentWillMount添加KeyboardListeners作爲解釋here

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow); 
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); 
    
  2. autoFocus添加到電子郵件/電話號碼/頁面上的任何其他「第一個」TextInput,以便在屏幕加載時,Keyboard p OPS-起來。

  3. _keyboardDidShow功能,即作爲KeyboardListener,執行如下:

    _keyboardDidShow(e) { 
        this.props.navigation.setParams({ 
         keyboardHeight: e.endCoordinates.height, 
         normalHeight: Dimensions.get('window').height, 
         shortHeight: Dimensions.get('window').height - e.endCoordinates.height, 
        }); 
    } 
    

    尺寸爲陣營本地的API,不要忘了導入它就像你導入任何陣營,本土零件。

  4. 此後,在重定向到下一個頁面,通過這些PARAMS,不要忘記讓他們傳遞到其他屏幕,爲了不失去這個數據:

    this.props.navigation.navigate('pageName', { params: this.props.navigation.state.params });