componentDidUpdate 与 componentDidMount

2024-01-01

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

  • DOM 可用
  • 并且属性发生了变化

问题:我需要将我的代码放入两个中吗componentDidUpdate and componentDidMount要不就componentDidUpdate就足够了吗?

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

    }

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

你必须同时使用两者。

组件DidMount() https://reactjs.org/docs/react-component.html#componentdidmount

组件安装后立即调用 componentDidMount()。需要 DOM 节点的初始化应该放在此处。如果您需要从远程端点加载数据,那么这是实例化网络请求的好地方。在此方法中设置状态将触发重新渲染。

组件DidUpdate() https://reactjs.org/docs/react-component.html#componentdidmount

更新发生后立即调用 componentDidUpdate()。初始渲染不会调用此方法.

您也可以将其放入render()方法似乎适合您的情况,因为您总是想检查焦点。那么你不需要把它放入componentDidMount() and componentDidUpdate()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

componentDidUpdate 与 componentDidMount 的相关文章

随机推荐