问题描述
当满足以下条件时,我需要确保输入元素获得焦点:
I need to make sure an input element is focused when the following is true:
- DOM 可用并且
- 属性已更改
问题:我需要将我的代码同时放在 componentDidUpdate
和 componentDidMount
中,还是只需要 componentDidUpdate
就足够了?
Question: Do I need to put my code in both componentDidUpdate
and componentDidMount
or just componentDidUpdate
would be suffice?
private makeSureInputElementFocused() {
if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
this.inputElement.focus();
}
}
componentDidMount() {
this.makeSureInputElementFocused(); // <-- do i need this?
}
componentDidUpdate() {
this.makeSureInputElementFocused();
}
推荐答案
您必须同时使用两者.
componentDidMount() 在组件安装后立即调用.需要 DOM 节点的初始化应该在这里进行.如果您需要从远程端点加载数据,这是实例化网络请求的好地方.在此方法中设置状态将触发重新渲染.
componentDidUpdate() 在更新发生后立即调用.初始渲染不会调用此方法.
您也可以将它放入 render()
方法中,这似乎适合您的情况,因为您总是想检查焦点.那么你就不需要把它放入componentDidMount()
和componentDidUpdate()
You also could place it into the render()
method which seems like it's appropriate for your case since you always want to check the focus. Then you don't need to put it into componentDidMount()
and componentDidUpdate()
这篇关于componentDidUpdate 与 componentDidMount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!