2016-09-06 4 views
0

코드를 지우려면 불필요한 코드를 제거합니다. 완전한 독립형 HTML 파일은 다음과 같습니다. 키를 누를 때, 입력이 포커스를 잃을 것으로 기대하지만 실제로는 그렇지 않습니다.구성 요소가 흐림으로 반응하지 않습니다. react.js

blur를 setTimeout (, 0)으로 묶으면 작동합니다. 하지만 왜 원본이 작동하지 않습니까?

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <script src="https://npmcdn.com/[email protected]/dist/react.js"></script> 
    <script src="https://npmcdn.com/[email protected]/dist/react-dom.js"></script> 
    <script src="https://npmcdn.com/[email protected]/browser.min.js"></script> 
    </head> 
<body> 
<div id="root"> 

</div> 
<script type="text/babel"> 
    class HelpBox extends React.Component { 
     constructor(props) { 
      super(props); 
      this.state = { 
      }; 
      window.addEventListener("keydown", this.keyDown.bind(this), false); 
     } 

     componentDidMount() { 
      this.refs.searchWord.focus(); 
     } 

     componentWillUpdate(nextProps, nextState) { 
      console.log('will blur', this.refs.searchWord); 
      this.refs.searchWord.blur(); 
     } 

     keyDown(e) { 
      this.setState({}); 
     } 

     render() { 
      return <div> 
       <input key="search" ref="searchWord" className="search" type="text" 
       /> 
      </div> 
     } 
    } 

    ReactDOM.render(
      <HelpBox/>, 
      document.getElementById('root') 
    ); 
</script> 
</body> 
</html> 

해결

: 나는 다음() 렌더링으로 반응에 의해 복원 componentWillUpdate에 DOM을 만졌다. 그것은 React가 LOL을해야하는 것입니다.

답변

0

keydown 이벤트는 blurfocus 이벤트 as default을 트리거합니다. setTimeout이 없으면 this.refs.searchWord.blur()은 보다 먼저 실행됩니다. this.refs.searchWord.blur()이 스택에 있기 때문입니다. setTimeout을 사용하면 this.refs.searchWord.blur()이 대기열에 저장되며 이는 this.refs.searchWord.blur()이 기본값 focus 및 기타 기능이 스택에 따라 실행됨을 의미합니다. 스택, 대기열 및 이벤트 루프에 익숙하지 않은 경우 this video

+0

답장을 보내 주셔서 감사합니다. 그러나 당신이 올바른 이유를 핀으로 생각하지 마십시오. 1. 반응을 사용하지 않으면 keydown 콜백에서 blur()가 좋습니다. https://jsfiddle.net/oss3jfLy/ – user147932

+0

2. 입력 요소에 onFocus 및 onBlur를 바인딩합니다. 그들은 해고되지 않았습니다. – user147932

+0

이러한 이벤트는 DOM 요소에서 발생합니다. onblur'와'$ ('. search'). onfocus' on chrome dev. 이벤트가 트리거되는 것을 볼 수 있습니다. –