this.refs.something返回" undefined"

时间:2016-02-05 17:26:33

标签: javascript reactjs react-jsx

我有一个定义了ref的元素,最终会被渲染到页面中:

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

我想访问像offset...之类的DOM元素属性。但是,我不断得到undefined,而且我还没有想到最微妙的想法。经过一些搜索后,很明显refs仅适用于一个文件,但除了这一页之外,我没有在任何地方使用此文件。我这样说是为了记录它:

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

导致这种情况的原因是什么?

6 个答案:

答案 0 :(得分:35)

在装入子组件之前,请检查您是否在访问ref。例如。它在componentWillMount中不起作用。在安装元素后自动调用ref相关回调的不同模式是 -

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

您也可以使用此表示法将深层嵌套中的已装入元素 -

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

答案 1 :(得分:28)

使用refs的正确位置是特定的React生命周期方法,例如ComponentDidMountComponentDidUpdate

您无法从refs方法中引用render()Read more about the cautions of working with refs here.

如果您将console.log('REFS', this.refs.russian);来电转移到ComponentDidMountComponentDidUpdate生命周期方法(假设您使用的是React&gt; = 14),则不应该未定义结果。

更新:根据上面的警告链接无法对无状态组件起作用

答案 2 :(得分:4)

从React版本16.4开始更新

在您的构造方法中,像这样定义您的引用

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

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

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

例如,如果您想在安装组件时集中精力

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

引用Refs Documentation React

答案 3 :(得分:0)

我在表单验证方法中遇到类似的问题,试图分配this.ref.current.reportValidity()

validate = () => {}而不是validate() {}的方式写我这样做的方法帮助了我,但我不确定为什么,只是我从过去工作中的习惯中得到的回忆经验给了我这个。希望它能有所帮助,并能有人请澄清这个答案,为什么它可能会确切起作用。

答案 4 :(得分:0)

如果要使用Style导出类,请移除并默认导出默认值。

答案 5 :(得分:0)

您应该将Console.log放在函数example(){...}中,而不是将其放入其中:

example=()=>{....}
相关问题