this.refs.something returns “undefined”

前端 未结 6 1689
野趣味
野趣味 2020-12-08 03:52

I have an element with a ref that is defined and ends up getting rendered into the page :

    
... <
6条回答
  •  生来不讨喜
    2020-12-08 04:35

    The correct place to work with refs is inside specific React lifecycle methods e.g. ComponentDidMount, ComponentDidUpdate

    You cannot reference refs from the render() method. Read more about the cautions of working with refs here.

    If you move your console.log('REFS', this.refs.russian); call to ComponentDidMount or ComponentDidUpdate lifecycle methods (assuming you are on React >= 14) you should not get undefined as a result.

    UPDATE: also refs will not work on stateless components per the caution link above

提交回复
热议问题