react hooks基础demo

hooks基础demo

import React,{useState,useEffect,createContext,useContext,useMemo,memo,useRef,PureComponent} from 'react'

const CountText = createContext();

//react hooks写法
/*function Counter(props) {
    const count = useContext(CountText);
    return(
        

{count}

) }*/
// Counter函数写法,如果使用ref就必须写成class /*const Counter = memo(function Counter(props){ console.log('counter render'); return(

{props.count}

) })*/
class Counter extends PureComponent{ speak(){ console.log('speak'); } render(){ let {props} = this; return( <h1 onClick={props.clickCounter}>{props.count}</h1> ) } } // 自定义hook,命名必须以use开头 function useCount(defaultCount){ const [myCount,setMyCount] = useState(defaultCount); const changeMyCount = ()=>{ setMyCount(myCount+1) } useEffect(()=>{ document.querySelector("#changeMyCount").addEventListener('click',changeMyCount,false) },[myCount]) return [myCount,setMyCount]; } const Hook = function () { const [myCount,setMyCount] = useCount(0) const [count,setCount] = useState(0); const [name,setName] = useState('hello world'); const counterRef = useRef(); const [size,setSize] = useState({ width:document.documentElement.clientWidth, height:document.documentElement.clientHeight }) const onResize = ()=>{ setSize({ width:document.documentElement.clientWidth, height:document.documentElement.clientHeight }) } const changeCount = ()=>{ setCount(count+1) console.log(count) } const changeSize = ()=>{ console.log('size') } const clickCounter = ()=>{ console.log(count) } const getRef = () => { //获取Conter组件的speak方法 counterRef.current.speak() } useEffect(()=>{ document.title=count; }) useEffect(() => { window.addEventListener('resize',onResize,false); return () => { window.removeEventListener('resize',onResize,false); } },[]) // count改变调用 useEffect(()=>{ console.log(count) },[count]) useEffect(()=>{ document.querySelector("#change").addEventListener('click',changeCount,false) },[count]) useEffect(()=>{ document.querySelector("#size").addEventListener('click',changeSize,false) return( document.querySelector("#size").removeEventListener('click',changeSize,false) ) }) useEffect(()=>{ document.querySelector("#btn").addEventListener('click',getRef,false) },[counterRef]) const double = useMemo(() => { return count*2; },[count==3]) //当count==3,这个才有效,这里也可以直接是count const half = useMemo(() => { return double/2; });//可以依赖于上面的useMemo return( <div> <button onClick={()=>{setCount(count+1)}}>{count}</button> <button onClick={()=>{setName('你好,react hook')}}>{name}</button> <button id='change'>使用useEffect绑定事件</button> <button id='btn'>使用useRef获取Counter</button> {size.width}*{size.height} <br/> {count%2==0 ?(<span id="size">我是偶数</span>) :(<span id="size">我是奇数</span>) } {/* userContext: */} <Counter ref={counterRef} count={count} clickCounter={clickCounter}/> {double}--{half} <br/> <button id='changeMyCount'>自定义hook</button> <h3>自定义hook:{myCount}</h3> </div> ) } export default Hook

你可能感兴趣的:(react hooks基础demo)