zoukankan      html  css  js  c++  java
  • [React] Manipulate the DOM with React refs

    React is really good at creating and updating DOM elements, but sometimes you need to work with them yourself. A common use case for this is when you’re using a third party library that wasn’t built for or with React specifically. To do this, we need to have some value that’s associated with our component (like state) to store a reference to the DOM element, but doesn’t trigger re-renders when it’s updated (unlike state). React has something specifically for this and it’s called a ref.

    You create a ref object with the useRef hook and that object’s current property is the current value of the ref. It can be anything, but if you pass that ref object to a component as a prop called ref, then React will set the current property to the DOM element it creates so you can reference it and manipulate it in your useEffect hook.

    In this lesson we’ll get to see how that works with a cool library called vanilla-tilt.

    function Tilt({ children }) {
          const tiltRef = React.useRef();
    
          // refs provide a way to access DOM nodes or React elements created in the render method.
    // we need to access DOM thought ref, so we need to render the DOM first, useEffect hook
    // is the prefect place to do it.
    React.useEffect(() => { // useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). const tiltNode = tiltRef.current; // The returned object will persist for the full lifetime of the component. const vanillaTiltOptions = { max: 25, speed: 400, glare: true, 'max-glare': 0.5 }; // Initiating VanillaTilt and passing tiltNode and vanillaTiltOptions VanillaTilt.init(tiltNode, vanillaTiltOptions); return () => { // ensuring that any node refs in memory get garbage collected // prevent memory leaks tiltNode.vanillaTilt.destroy(); }; // adding a dependencies array, to avoid multiple renders }, []); return ( // Referencing the useEffect hook return <div ref={tiltRef} className="tilt-root"> <div className="tilt-child">{children}</div> </div> ); }
  • 相关阅读:
    unreal python commandlet print log
    三维空间坐标系变换公式
    Android Volley初探:Volley基本用法
    Android View学习笔记(四):Scroller的原理剖析及使用(下)
    Android View学习笔记(三):Scroller的原理剖析及使用(上)
    Android View学习笔记(二):View滑动方式总结
    Android View学习笔记(一):View基础知识
    获取NavigationBar状态与高度
    解决RecyclerView.getChildAt(Position)崩溃
    RecyclerView瀑布流的那些坑
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13597968.html
Copyright © 2011-2022 走看看