I remove the unnecessary code to make the code clear. The full standalone html file is as follow. When key pressed, I expect the input to lose focus, but actually it doesn't.
If I enclose blur with setTimeout(, 0), it will work. But why the original does not work?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://npmcdn.com/react@15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom@15.3.1/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core@5.8.38/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>
Resolved: I touched DOM in componentWillUpdate, which is then restored by React in render(). That's what React should do LOL.