【问题标题】:'ref' declaration in pure react纯反应中的“参考”声明
【发布时间】:2021-03-27 00:51:01
【问题描述】:

我正在参加 Dan abramov 在 egghead.io 上的 redux 课程,他创建了一个输入字段并分配了一个 ref 属性,这看起来像是一个功能分配。代码如下,

<input ref={node => {input = node;}} />
    
<button onClick={() => { input.value = ''}> ADD</button>

你能解释一下吗,提前谢谢!

【问题讨论】:

    标签: html reactjs ref


    【解决方案1】:

    这是一个名为callback refs 的功能。如果你将一个函数传递给ref,它将以 DOM 元素作为参数被调用,你可以用它做任何你想做的事情。在您的示例中,该元素被分配给 input 变量。

    在某些情况下,您必须“逃避” React 模型并需要访问底层 DOM 元素(例如,用于控制焦点),而 refs 是一种(?)方法。

    【讨论】:

    • 你似乎是对的兄弟,谢谢你的回答
    【解决方案2】:

    当我们想要访问 dom 元素对象时,我们使用“ref”。这是获取dom对象的react方式。

    您可以使用传统方式获取 dom 对象 document.getElementById("inputId") 但问题是您需要在正确的生命周期中使用它,否则您可能无法获得元素。

    ref 的另一个优点是,如果组件被销毁,您的 ref 对象也将被销毁。

    例子:

    <input id="inputId" ref={node => {input = node;}} />
        
    <button onClick={() => { input.value = ''}> ADD</button>
    
    console.log(input)
    
    console.log(document.getElementById("inputId"))
    

    两个控制台都会指向同一个dom元素

    查看此处了解更多详情https://reactjs.org/docs/refs-and-the-dom.html

    【讨论】:

      【解决方案3】:

      这可能会有所帮助

      const inputRef = React.useRef(null); // create ref of input using Hooks
      
      <input ref={inputRef} /> // render input field and assign ref to it
          
      // render button and when click on it, it reassign the input value to empty     
      <button onClick={() => { inputRef.current.value = '' } > ADD </button>
      

      【讨论】:

      • 这似乎并没有解决 OP 的问题。
      • ya @FelixKling,没问题,我从这个道具中学到了,很好的答案
      猜你喜欢
      • 2016-11-26
      • 2013-07-31
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多