把工程里无关代码去掉,剩下下面这段代码。按下键盘的时候,componentWillUpdate函数执行了,但blur()函数没有产生效果,这个是为什么?
注:有很多办法可以练过这个问题,比如componentDidUpdate,比如setTimeout(,0),但为什么写在componentWillUpdate里不可以。
<!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>
<p id="root">
</p>
<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 <p>
<input key="search" ref="searchWord" className="search" type="text"
/>
</p>
}
}
ReactDOM.render(
<HelpBox/>,
document.getElementById('root')
);
</script>
</body>
</html>
class HelpBox extends React.Component {
}
用这个componentDidUpdate,监听keyup,输入完成失去焦点