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

 

 

posted @ 2019-05-21 13:52  Zhentiw  阅读(241)  评论(0编辑  收藏  举报