简体   繁体   English

React将DOM引用暴露给父组件

[英]React Exposing DOM Refs to Parent Components

I'm learning from the docs but don't get the line below 我正在从文档中学习,但是没有得到以下内容

inputRef={el => this.inputElement = el}

Why is there a = el at the end? 为什么最后有一个= el Isn't inputRef just supposed to be a function to grab a reference to the input? 是不是inputRef应该是一个获取输入引用的函数?

We can use ref in 2 ways, first way is pass a string value as a ref and access the component as: 我们可以用2种方式使用ref,第一种方法是将字符串值作为ref传递并访问组件:

inputRef="input"
...
myInput = this.refs.input

But this is an old way and it may be deprecated in next versions. 但这是一种古老的方式,可能会在下一版本中弃用。 The second way is to pass a function to ref, which fired when a component is mounted and ready to work. 第二种方法是将函数传递给ref,该函数在安装组件并准备工作时触发。 Also, this function will receive the target element as a parameter. 此外,此函数将接收目标元素作为参数。

To clarify this moment let's write the same code in ES5: 为了澄清这一刻,让我们在ES5中编写相同的代码:

inputRef={ function(input) {_this.inputElement = input;}

So, in this case, you've added inputElement key to parent component that contains the input. 因此,在这种情况下,您已将inputElement键添加到包含输入的父组件。 And you can access it via this.inputElement 您可以通过this.inputElement访问它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM