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()
    
          React.useEffect(() => {
            const tiltNode = tiltRef.current
            const vanillaTiltOptions = {
              max: 25,
              speed: 400,
              glare: true,
              'max-glare': 0.5,
            }
            VanillaTilt.init(tiltNode, vanillaTiltOptions)
            return () => {
              tiltNode.vanillaTilt.destroy()
            }
          }, [])
    
          return (
            <div ref={tiltRef} className="tilt-root">
              <div className="tilt-child">{children}</div>
            </div>
          )
        }
  • 相关阅读:
    【学习篇】JavaScript可折叠区域
    hdu 2201 (简单数学概率)
    hdu 2552 (这题很强大)
    hdu 2212 (简单数学)
    hdu 2124 (赤裸裸的贪心)
    hdu 2570 (贪心)
    hdu 2401 (简单数学)
    hdu 2537(水)
    hdu4432
    hdu 1181 (搜索BFS,深搜DFS,并查集)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12595253.html
Copyright © 2011-2022 走看看