Day 12 - 那个被我忘记的 ref / useRef / createRef 上

如果有错误,欢迎留言指教~ Q_Q 还没写完辣

对的 我一直只记得 ref 是取得的 DOM 的一种偷懒方式

因为在 vue 里面,我也只是这麽用der ><

ref 可以让我们取得 DOM

<input> 设定 ref={inputRef}

当画面上找到 inputRef 後
ref 的 current 就会 callback 相对应的 DOM 节点 : <input type="text"></input>
当确定他们存在,就可以去控制拉~~~

例如控制 input 的 focus

const inputRef = useRef(null);
console.log(inputRef);
// -> { current: null }

<input
    type="text"
    ref={(ref) => {
      ref.focus();
      console.log(ref);
      // -> <input type="text"></input>
    }}
/>
import React, { useRef } from "react";

export default function App() {
  const inputRef = useRef(null);

  return (
    <div className="App">
      <input type="text" ref={inputRef} />
      <button
        onClick={() => {
          inputRef.current && inputRef.current.focus();
        }}
      >
        focus input
      </button>
    </div>
  );
}

参考连结:

  1. https://zh-hant.reactjs.org/docs/hooks-reference.html#useref
  2. https://zh-hant.reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
  3. https://zh-hant.reactjs.org/docs/refs-and-the-dom.html

<<:  Day 23 - 新的一年离职同事的惊喜专案包(下)

>>:  {DAY 15} Pandas 学习笔记 part.1

Day 26【Deploy NFT - Lazy-Minting & Smart Contract】Right Click and Save Image As

【前言】 接下来我们要进到整个 Project 重头戏中的重头戏啦,当我们都具备好图档以及 Met...

【没钱买ps,PyQt自己写】Day 21 - 透过 PyQt 实现滑鼠监听总整理,完全掌握滑鼠控制 (listen mouse)

看完这篇文章你会得到的成果图 前言 这一篇我们会拿现有的 day 17 成品来改, 我们这篇主要要学...

网路设备(上)

主机组好後,Server网路环境也是相当重要的一环呢! 在正式安装unRaid前会先谈各网路设备的原...

Day10 PHP数据类型--基本类型之数字与布尔型

这是今天要介绍的详细一点的数据类型: 整型(int/integer) 浮点型(float) 布尔型(...

JS 09 - 类别函式

大家好! 今天要介绍的是类别函式,就是将前几天的主题全都打包在一起的写法。 那麽油门踩下去吧! 物件...