其他分享
首页 > 其他分享> > React hooks 获取 dom 引用

React hooks 获取 dom 引用

作者:互联网

React Hooks are now available in React 16.8. There are 10 different hooks, you can read about them here. When I needed a ref to a dom element yesterday I reached for useRef.

const containerRef = useRef(null);

  

This isn’t a ref to anything unless you pass the ref to a tag.

return (<div ref={containerRef}></div>);

  

Now the ref will be assigned a dom element that you can use. In this example I’m using the useEffect hook to execute a side effect after the render takes place. Use the current attribute to access the current dom node.

useEffect(() => {
  containerRef.current.style = 'background-color: green;'
})

 

标签:current,useRef,dom,hooks,React,ref
来源: https://www.cnblogs.com/gitnull/p/14308286.html