gpt4 book ai didi

reactjs - componentDidUpdate 与 componentDidMount

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

当满足以下条件时,我需要确保输入元素获得焦点:

  • DOM 可用
  • 并且属性已更改

问题:我是否需要将代码同时放入 componentDidUpdatecomponentDidMount 中,还是仅使用 componentDidUpdate 就足够了?

    private makeSureInputElementFocused() {
if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
this.inputElement.focus();
}

}

componentDidMount() {
this.makeSureInputElementFocused(); // <-- do i need this?
}
componentDidUpdate() {
this.makeSureInputElementFocused();
}

最佳答案

你必须同时使用两者。

componentDidMount()

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()

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/

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