2017-03-09 30 views
2

假設我有一個絕對位於屏幕底部的視圖。該視圖包含一個文本輸入。當文本輸入焦點時,我希望視圖的底部觸摸鍵盤的頂部。反應本機制作視圖「擁抱」鍵盤頂部

我一直在與KeyboardAvoidingView搞混,但鍵盤一直在我的視圖。是否可以使這個工作的位置絕對?

我還可以嘗試其他方法嗎?謝謝!

回答

4

前幾天我有同樣的問題(雖然我與的TextInput一個複雜的視圖作爲一個孩子),並希望不僅將TextInput被集中,但整體視圖被「附加」到鍵盤。最後是爲我工作是以下代碼:

constructor(props) { 
    super(props); 
    this.paddingInput = new Animated.Value(0); 
} 

componentWillMount() { 
    this.keyboardWillShowSub = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow); 
    this.keyboardWillHideSub = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide); 
} 

componentWillUnmount() { 
    this.keyboardWillShowSub.remove(); 
    this.keyboardWillHideSub.remove(); 
} 

keyboardWillShow = (event) => { 
    Animated.timing(this.paddingInput, { 
     duration: event.duration, 
     toValue: 60, 
    }).start(); 
}; 

keyboardWillHide = (event) => { 
    Animated.timing(this.paddingInput, { 
     duration: event.duration, 
     toValue: 0, 
    }).start(); 
}; 

render() { 
     return (
      <KeyboardAvoidingView behavior='padding' style={{ flex: 1 }}> 
       [...] 
       <Animated.View style={{ marginBottom: this.paddingInput }}> 
        <TextTranslateInput /> 
       </Animated.View> 
      </KeyboardAvoidingView> 
     ); 
    } 

其中[..]你有其他意見。

+0

謝謝!這工作完美。 – Zach

+0

我很高興聽到:) – jazzdle

+0

可以證實,這是一個非常漂亮的解決方案。感謝您花時間發佈此信息! – Bill

0

您可以使用flexbox將元素放置在底部。這是一個簡單的例子 -

render() { 
    return (
     <View style={styles.container}> 
     <View style={styles.top}/> 
     <View style={styles.bottom}> 
      <View style={styles.input}> 
      <TextInput/> 
      </View> 
     </View> 
     </View> 
    ); 
    } 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
    top: { 
    flex: .8, 
    }, 
    bottom: { 
    flex: .2, 
    }, 
    input: { 
    width: 200, 
    }, 
});