this.refs.something returns "undefined"

this.refs.something returns "undefined"

本文关键字:quot undefined returns refs something this      更新时间:2023-09-26

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

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

我想访问 DOM 元素属性,例如offset...或其他属性。然而,我一直在undefined,我不知道为什么。经过一些搜索,很明显refs仅适用于一个文件,但除了这一页之外,我没有在任何地方使用它。我这样说是为了记录它:

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

可能是什么原因造成的?

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

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

您也可以使用此符号在深度嵌套中获取挂载的元素 -

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

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

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

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

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

自 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();
 }
参考

参考文档反应

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

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

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

与其将控制台.log放在函数中,不如将其放入函数example(){...}

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