代码之家  ›  专栏  ›  技术社区  ›  Rico Kahler

“useref”和“createref”有什么区别?

  •  2
  • Rico Kahler  · 技术社区  · 6 年前

    当我偶然发现钩子文档时 useRef .

    看看他们的例子

    function TextInputWithFocusButton() {
      const inputEl = useRef(null);
      const onButtonClick = () => {
        // `current` points to the mounted text input element
        inputEl.current.focus();
      };
      return (
        <>
          <input ref={inputEl} type="text" />
          <button onClick={onButtonClick}>Focus the input</button>
        </>
      );
    }
    

    看起来像 乌瑟夫 可替换为 createRef .

    function TextInputWithFocusButton() {
      const inputRef = createRef(); // what's the diff?
      const onButtonClick = () => {
        // `current` points to the mounted text input element
        inputRef.current.focus();
      };
      return (
        <>
          <input ref={inputRef} type="text" />
          <button onClick={onButtonClick}>Focus the input</button>
        </>
      );
    }
    

    为什么我需要一个钩子作为参考?为什么 乌瑟夫 存在?

    2 回复  |  直到 6 年前
        1
  •  5
  •   Ryan Cogswell    6 年前

    区别在于 createRef 将始终在基于类的组件中创建一个新的引用,通常在构造期间将该引用放在实例属性中(例如 this.input = createRef() )在函数组件中没有此选项。 useRef 注意每次返回与初始渲染相同的引用。

    下面是一个示例应用程序,演示了这两个函数的行为差异:

    import React, { useRef, createRef, useState } from "react";
    import ReactDOM from "react-dom";
    
    function App() {
      const [renderIndex, setRenderIndex] = useState(1);
      const refFromUseRef = useRef();
      const refFromCreateRef = createRef();
      if (!refFromUseRef.current) {
        refFromUseRef.current = renderIndex;
      }
      if (!refFromCreateRef.current) {
        refFromCreateRef.current = renderIndex;
      }
      return (
        <div className="App">
          Current render index: {renderIndex}
          <br />
          First render index remembered within refFromUseRef.current:
          {refFromUseRef.current}
          <br />
          First render index unsuccessfully remembered within
          refFromCreateRef.current:
          {refFromCreateRef.current}
          <br />
          <button onClick={() => setRenderIndex(prev => prev + 1)}>
            Cause re-render
          </button>
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    Edit 1rvwnj71x3

        2
  •  3
  •   Joe Clay    6 年前

    createRef 总是返回一个新的引用,通常将其存储为类组件实例上的字段。 useRef 收益率 同样的裁判 函数组件实例的每次呈现时。这允许在渲染之间保持引用的状态,尽管您没有将其明确存储在任何位置。

    在第二个示例中,将在每次渲染时重新创建引用。