reactjs - componentDidUpdate 与 componentDidMount

标签 reactjs

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

  • 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/

相关文章:

node.js - 如何在 Next.js 中设置没有自定义服务器的 X-Frame-Options header ?

javascript - <Header> 元素(<Avatar>、<Text>)堆叠在手机导航栏下 - react - native

javascript - react : Traversing nested Objects in state to prevent duplicates – most performant way?

javascript - 在 React JS 中更新数组会覆盖旧值

reactjs - 为什么不应该将 child 作为 Prop 传递?

javascript - 使用 React Router v4 是否可以在子组件中创建多级路由?

javascript - Nextjs : How to register the quill-blot-formatter to dynamically imported react-quill on client side rendering only?

javascript - 函数是否作为 props 在此代码中传递?

reactjs - 配置多个下一个插件 : withMDX, withBundleAnalyzer

javascript - 仅当不靠近 messages div 的底部时,保持滚动位置才有效