Javascript this.refs.something 返回“未定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35230020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:26:04  来源:igfitidea点击:

this.refs.something returns "undefined"

javascriptreactjsreact-jsx

提问by John Doe

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

我有一个ref已定义并最终呈现到页面中的元素:

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

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

我想访问 DOM 元素属性之类的offset...。然而,我不断得到undefined,我不知道为什么。经过一番搜索,很明显refs它只适用于一个文件,但除了这一页之外,我没有在任何地方使用它。我说这个是为了记录它:

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

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

What could be causing this?

什么可能导致这种情况?

采纳答案by jurassix

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

正确的工作位置refs是在特定的 React 生命周期方法中,例如ComponentDidMountComponentDidUpdate

You cannot reference refsfrom the render()method. Read more about the cautions of working with refshere.

您不能refsrender()方法中引用。在此处阅读有关使用注意事项的更多信息refs

If you move your console.log('REFS', this.refs.russian);call to ComponentDidMountor ComponentDidUpdatelifecycle methods (assuming you are on React >= 14) you should not get undefinedas a result.

如果您将console.log('REFS', this.refs.russian);调用移动到ComponentDidMountComponentDidUpdate生命周期方法(假设您在 React >= 14 上),您不应该因此得到undefined

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

更新:根据上面的警告链接,refs 也不适用于无状态组件

回答by hazardous

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-

在安装子组件之前检查您是否没有访问 ref。例如它在componentWillMount. 在元素安装后自动调用与 ref 相关的回调的不同模式是 -

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

回答by Adeel Imran

Update since React version 16.4

从 React 16.4 版开始更新

In your constructor method define your ref like this

在您的构造函数方法中,像这样定义您的 ref

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

In your render where you are using refdo this.

在您使用的渲染中ref执行此操作。

<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

参考Refs 文档 React

回答by Statik

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

我在表单验证方法中遇到了类似的问题,试图分配 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.

写出我正在做的方法,validate = () => {}而不是validate() {}帮助我,但我不完全确定究竟是为什么,只是我从过去工作经验中的习惯中记住的东西给了我这个。希望它有所帮助,并且有人可以澄清这个答案,为什么这可能完全有效。

回答by v? vi?t hoàng v?

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

如果您使用Style导出类,请正常删除并导出默认值。

回答by Maykel

Instead of putting your Console.log inside the function example(){...}you should put it inside:

而不是将你的 Console.log 放在函数中,example(){...}你应该把它放在里面:

example=()=>{....}