当满足以下条件时,我需要确保输入元素获得焦点:
- DOM 可用
- 并且属性已更改
问题:我是否需要将代码同时放入 componentDidUpdate
和 componentDidMount
中,还是仅使用 componentDidUpdate
就足够了?
private makeSureInputElementFocused() {
if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
this.inputElement.focus();
}
}
componentDidMount() {
this.makeSureInputElementFocused(); // <-- do i need this?
}
componentDidUpdate() {
this.makeSureInputElementFocused();
}
最佳答案
你必须同时使用两者。
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
您还可以将其放入 render()
方法中,这似乎适合您的情况,因为您总是想检查焦点。那么就不需要将其放入 componentDidMount()
和 componentDidUpdate()
关于reactjs - componentDidUpdate 与 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46686386/