this.refs.something returns “undefined”

﹥>﹥吖頭↗ 提交于 2019-12-18 10:48:34

问题


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

    <div ref="russian" ...>
       ...
    </div>

I want to access the DOM element properties like offset... or something. However, I keep getting undefined and I haven't the faintest idea why. After some searching it's clear that refs are only applicable to one file but I'm not using this anywhere besides this one page. I'm saying this to log it:

console.log('REFS', this.refs.russian);

What could be causing this?


回答1:


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




回答2:


Check that you are not accessing ref before the child component has been mounted. E.g. it doesn't work in componentWillMount. A different pattern which auto invokes ref related callback after the element has been mounted is this-

<div ref={(elem)=>(console.log(elem))}/>

You can use this notation to get mounted elements in deep nesting as well -

<div ref={this.props.onMounted}/>



回答3:


Update since React version 16.4

In your constructor method define your ref like this

constructor(props) {
  super(props);
  this.russian = React.createRef();
}

In your render where you are using ref do this.

<input
  name="russian"
  ref={this.russian} // Proper way to assign ref in react ver 16.4
/>  

For e.g if you want to have focus when component mounts do this

componentDidMount() {
  console.log(this.russian); 
  this.russian.current.focus();
 }

Reference Refs Documentation React




回答4:


I was having a similar issue in my form validation methods, trying to assign this.ref.current.reportValidity()

Writing the method I was doing this in as validate = () => {} instead of validate() {} helped me out, but I'm not totally sure why exactly, just something I remembered from habits I had in my past work experience that gave me this. Hope it helps and could someone kindly clarify this answer with why this might work exactly.




回答5:


If you are exporting class withStyle, please remove and export default nomally.



来源:https://stackoverflow.com/questions/35230020/this-refs-something-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!