gpt4 book ai didi

javascript - HTMLElement.blur 方法在 componentWillReceiveProps 中不起作用

转载 作者:行者123 更新时间:2023-12-03 08:00:52 25 4
gpt4 key购买 nike

当从 componentWillReceiveProps 调用时,使用 HTMLElement.blur 似乎无法按预期工作,尽管 HTMLElement.focus 实际上 确实有效。

简单的重现案例(es2015使用babel):

class App extends React.Component {

constructor(props) {
super(props);

this.state = {
index: 0
};
}

componentWillMount() {
document.addEventListener("keydown", e => this.handleKeyDown(e));
}

handleKeyDown(e) {
let index = this.state.index;
switch (e.which) {
case 40: // up arrow
index = Math.max(0, index - 1);
break;
case 38: // down arrow
index++;
break;
}

this.setState({index});
}

render() {
return (
<div>
<SearchBox index={this.state.index} />
<p>Index: {this.state.index}</p>
</div>
);
}
}

class SearchBox extends React.Component {

componentWillReceiveProps(nextProps) {
if (nextProps.index === 0) {
console.log('focusing');
this.textbox.focus(); // this works
} else {
console.log('blurring');
this.textbox.blur(); // this doesn't
}
}

render() {
return (
<input type="text" ref={n => this.textbox = n} />
);
}
};

我创建了一个 JSBin here显示意外行为。

有人对此有解释吗?我对 React 生命周期有什么误解吗?

最佳答案

看起来这确实是错误的生命周期 Hook 。

当我重新阅读文档时发现了这个金 block :

Updating: componentDidUpdate

void componentDidUpdate(object prevProps, object prevState)

Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated.

来自here

我将相关代码移至 componentDidUpdate,现在一切按预期工作。

关于javascript - HTMLElement.blur 方法在 componentWillReceiveProps 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34582673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com