2017-03-15 1 views
0

기본적으로 폼이없는 로그인 페이지가 있으며 사용자가 enter를 누르면 로그인 버튼의 onClick을 트리거하려고합니다. React에서 버튼의 onClick on key를 트리거

난과 같이 페이지에 이벤트 리스너를 추가하는 시도 :

componentWillMount() { 
    const { handleKeyPress, username, password } = this.props; 
    document.addEventListener('keydown', (event, username, password) => handleKeyPress(event.key)); 
} 

문제는 그 청취자가 의미 요소 마운트는 소품 username을 것을 때 인스턴스화와 비밀번호가 초기 상태에되어 있는지 (즉, 빈).

비슷한 이유에서 componentWillReceiveProps에 이벤트 수신기를 추가하는 기능이 작동하지 않습니다.

기본적으로이 솔루션을 사용하면 이벤트 수신기의 함수에서 사용자 이름과 암호를 보내지 않고 대신에 이벤트 리스너의 함수가 정의 된 mapDispatchToProps의 상태에서 사용자 이름과 암호를 가져올 필요가 있습니다. 추악한 독방.

<button 
    onEnterKeyPress={() => handleLogin(this.props.username, this.propspassword)} 
> 
    Log in 
</button> 

그러나 내가 아는 한 그 일의 방법이 없습니다 .. :

은 내가 처음에 찾고 있던 것은 같은 기본적 온 클릭과 비슷하고 버튼에 리스너를 추가하는 것이 었습니다 희망을 갖고 나는 틀렸다! 누구나 아이디어가 있다면 공유하십시오.

답변

1
constructor() { 
    super(); 
    this.handleKeyPress = this.handleKeyPress.bind(this); 
} 

componentWillMount() { 
    document.addEventListener('keydown', this.handleKeyPress); 
} 

handleKeyPress(event) { 
    if (event.keyCode !== 13) return; 

    const {handleLogin, username, password} = this.props; 

    handleLogin(username, password); 
} 

componentWillUnmount() { 
    document.removeEventListener('keydown', this.handleKeyPress); 
} 
+0

대답 위 플러스 등의 작품과 같은 기능이 바인딩 : this.handleKeyPress = this.handleKeyPress.bind (이); MDTP에서 인라인으로 함수를 작성하는 것만 큼 좋지는 않지만 괜찮은 솔루션입니다. 감사! 답을 수락하고 답을 편집하고 제본을 추가하십시오. 또한 removeEventListener btw에 두 번째 인수를 추가해야합니다. –

+0

createClass를 사용할 경우 추가 바인딩이 필요하지만 필요하지 않습니다. :) 도와 드리겠습니다! –

관련 문제