[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);

 

 

    原文作者:Zhentiw
    原文地址: https://www.cnblogs.com/Answer1215/p/10899404.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞