zoukankan      html  css  js  c++  java
  • [React] Create a Persistent Reference to a Value Using React useRef Hook

    The useRef is a hook for creating values that persist across renders. In this lesson we'll learn how to use the useRef hook to measure the width of an element as it changes.

    import React, { useState, useEffect, useRef } from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    function useInput(defaultValue) {
      const [value, setValue] = useState(defaultValue)
    
      function onChange(e) {
        setValue(e.target.value)
      }
    
      return {
        value,
        onChange
      }
    }
    
    function App() {
      const input = useInput("");
      const messageRef = useRef();
    
      useEffect(() => {
        const boundingBox = messageRef.current.getBoundingClientRect();
        console.log(boundingBox.width);
      });
    
      return (
        <div className="App">
          <h1>How to useRef in React</h1>
          <input {...input} />
          <div>
            <span ref={messageRef}>{input.value}</span>
          </div>
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);

  • 相关阅读:
    工具安装
    Windbg调试
    SQL学习
    Pwnable小结
    how2heap总结
    堆利用小结
    栈溢出利用小结
    格式化字符串利用小结
    python 节假日爬取
    selenuim学习
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10899404.html
Copyright © 2011-2022 走看看