{values:{name:'Mary Poppins',email:'mary@example.com',password:'1234',plan:'free',},touched:{name:true,email:true,password:true,plan:true,},validity:{name:true,email:true,password:false,plan:true,},errors:{password:'Please lengthen this text to 8 characters or more',},clear:Function,clearField:Function,reset:Function,resetField:Function,setField:Function,}
importuseMediafrom'use-media';// Alternatively, you can import as:// import {useMedia} from 'use-media';constDemo=()=>{// Accepts an object of features to testconstisWide=useMedia({minWidth:1000});// Or a regular media query stringconstreduceMotion=useMedia('(prefers-reduced-motion: reduce)');return(<div>Screeniswide:{isWide?'😃':'😢'}</div>
);};
和useLayoutEffect:
import{useMediaLayout}from'use-media';constDemo=()=>{// Accepts an object of features to testconstisWide=useMediaLayout({minWidth:1000});// Or a regular media query stringconstreduceMotion=useMediaLayout('(prefers-reduced-motion: reduce)');return(<div>Screeniswide:{isWide?'😃':'😢'}</div>
);};
您可能还记得我写过一篇关于图像优化的文章,以及 API 如何IntersectionObserver成为一个方便的工具,用于在图像出现在视口时延迟加载图像。
这个钩子允许你使用这个很棒的 API:
importReact,{useRef,useState}from"react";import{useIntersectionObserver}from"react-hook-intersection-observer";constApp=()=>{constroot=useRef();// We need a ref to our "root" or our parent,consttarget=useRef();// We need a ref to our "target" or our child-to-watch,// Let's use a bit of state.const[isThingIntersecting,setThingIntersecting]=useState(false);// Here's our hook! Let's give it some configuration...useIntersectionObserver({root,target,// What do we do when it intersects?// The signature of this callback is (collectionOfIntersections, observerElement).onIntersect:([{isIntersecting}])=>setThingIntersecting(isIntersecting)});return(<divclassName="App"><h1>useIntersectionObserver</h1>
<h2>Thethingiscurrently{""}{!isThingIntersecting&&<spanstyle={{color:"red"}}>not</span>}{" "}
<spanstyle={{color:isThingIntersecting?"green":"black"}}>intersecting</span>
!</h2>
<divref={root}className="black-box"><divclassName="larger-box"><divref={target}>THETHING</div>
</div>
</div>
</div>
);};