본문 바로가기

react-native 공부

[reactnative]키보드 켜졌을 때 꺼졌을 때, 높이를 어케알까(keyboard event,show,hide,height)

반응형

디자인 수정 중에

 

채팅하는 페이지에서 input창을 누르면 키보드가 input창을 가려버렸다

즉 키보드가 올라와서  input창이 안보인다

 

 

 

ios에서만 이런현상이 보였는데

내가 짠게 아니라서 

걍 강제로 키보드가 올라왔을 때 -> 인풋창에 margin-bottom 을 줘서 올려버렸다

 


키보드가 올라왔을 때와 내려갔을 때의

이벤트를 받아야한다

 

 

먼저 import

import { Keyboard } from 'react-native';

라이브러리 기본 제공이다

 

 

 

이벤트 리스너 이다

componentDidMount () {

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    //키보드가 show 했을 때 
    //this._keyboardDidShow 함수 실행
    
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
    //키보드가 Hide 했을 때 
    //this._keyboardDidHide 함수 실행

}

 

 

실행 함수

 _keyboardDidShow () {                //키보드 show 했을때 실행
    alert('Keyboard Shown'); 
    Height= e.endCoordinates.height;
  }

  _keyboardDidHide () {              //키보드 hide 했을때 실행
    alert('Keyboard Hidden');
  }

 

e.endCoordinates.height//를 사용하면 키보드 높이를 구할 수 있다

 


예)

 

내가만든 state 값

    super(props);
    this.state = {
      keyboardH: 0,  //대충 키보드height라는 뜻
    };

렌더 될때 0으로 시작한다

 

 

 

대충 input 태그랑 TouchableOpacity가 있는

<View>의 css 이다 

              <View
                style={{
                  display: 'flex',
                  backgroundColor: 'white',
                  flexDirection: 'row',
                  justifyContent: 'center',
                  marginBottom: this.state.keyboardH, //바텀에 amargin값 지금은 0
                }}>
                <TextInput/>
                <TouchableOpacity
                  <Image/>
                </TouchableOpacity>
              </View>

 

 

 

 

키보드가 없으니 바닥에 잘 붙어있다

 

 

 

 

 

키보드가 show 했을 때 

keyboardH 최기화 (ios에서만 이런 현상이라 Platform.OS를 사용했다)

hide 했을 때 초기화

 

 _keyboardDidShow = (e) => {
    this.setState({
      keyboardH: Platform.OS === 'ios' ? e.endCoordinates.height - 50 : 0,
      //높이에 -50정도 해주니까 얼추 맞았다
    });
  };

  _keyboardDidHide = () => {
    this.setState({
      keyboardH: 0,
    });
  };

 

 

결과:

 

 어쨋던 올라온다.

 

 

 

 

 

 

참고:

stackoverflow.com/questions/46587006/how-to-get-a-height-of-a-keyboard-in-react-native

 

How to get a height of a Keyboard in React-Native?

I am using React-Navigation in my app and the app consists of StackNavigator with multiple screens, some screens of which have TextInput with autoFocus={true} Problem: on these screens when the

stackoverflow.com

 

 

 

광고눌러줬으면좋겠어요

반응형