[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> ) }
相关文章
- React_Fiber机制
- 【油猴脚本】在 Iconfont 上直接复制 React component 代码
- React Error: Failed at the xxx@0.1.0 start script 'react-scripts start'.
- 从一次react异步setState引发的思考
- React源码解读之更新的创建
- React的useLayoutEffect和useEffect执行时机有什么不同
- react源码分析:深度理解React.Context
- react源码调试
- React魔法堂:echarts-for-react源码略读
- 用于构建用户界面的JavaScript库--->React
- React 组件基础
- 第120期:Next.js 和 React 到底该选哪一个?
- React中的setState为什么是异步的?
- 深入react源码看setState究竟做了什么?
- 一步步实现React-Hooks核心原理4
- react的jsx和React.createElement是什么关系?面试常问5
- ORA-01378: The logical block size (string) of file string is not compatible with the disk sector size (media sector size is string and host sector size is string) ORACLE 报错 故障修复 远程处理
- ORA-28077: The attribute specified (string) exceeds the maximum length. ORACLE 报错 故障修复 远程处理
- ORA-31692: The following SQL statement failed trying to insert a row into the Master table: string ORACLE 报错 故障修复 远程处理
- ORA-48410: The trace path exceeds the maximum number [string] ORACLE 报错 故障修复 远程处理
- ORA-64107: The XMLIndex has been successfully altered but the metadata could not be updated. ORACLE 报错 故障修复 远程处理
- ORA-01378: The logical block size (string) of file string is not compatible with the disk sector size (media sector size is string and host sector size is string) ORACLE 报错 故障修复 远程处理
- Discover the Power of Linux with YLMF: The UserFriendly Operating System(linuxylmf)
- Unveiling the Evolution of Linux: The Journey of the 0.11 Version(linux0.11)