首页 > componentWillUpdate 里的 blur 没有执行是为什么?

componentWillUpdate 里的 blur 没有执行是为什么?

把工程里无关代码去掉,剩下下面这段代码。按下键盘的时候,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>
<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>

class HelpBox extends React.Component {

constructor(props) {
    super(props);
    this.state = {
    };
    window.addEventListener("keyup", this.keyDown.bind(this), false);
}

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

componentDidUpdate(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>
}

}
用这个componentDidUpdate,监听keyup,输入完成失去焦点

【热门文章】
【热门文章】