标签:sem isp inpu const nbu ext pre containe org
import React, { useState } from ‘react‘; function Example() { // 声明一个叫 "count" 的 state 变量 const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
componentDidMount
,componentDidUpdate
和 componentWillUnmount
这三个函数的组合。import React, { useState, useEffect } from ‘react‘; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
React.createContext
的返回值)并返回该 context 的当前值。当前的 context 值由上层组件中距离当前组件最近的 <MyContext.Provider>
的 value
prop 决定。当组件上层最近的 <MyContext.Provider>
更新时,该 Hook 会触发重渲染,并使用最新传递给 MyContext
provider 的 context value
值。import React, { useState , createContext , useContext} from ‘react‘; const CountContext = createContext() function Example4(){ const [ count , setCount ] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={()=>{setCount(count+1)}}>click me</button> <CountContext.Provider value={count}> <Counter /> </CountContext.Provider> </div> ) } function Counter(){ const count = useContext(CountContext) //一句话就可以得到count return (<h2>{count}</h2>) } export default Example4;
useState
的替代方案。它接收一个形如 (state, action) => newState
的 reducer,并返回当前的 state 以及与其配套的 dispatch
方法。import React, { useReducer } from ‘react‘; function ReducerDemo(){ const [ count , dispatch ] =useReducer((state,action)=>{ switch(action){ case ‘add‘: return state+1 case ‘sub‘: return state-1 default: return state } },0) return ( <div> <h2>现在的分数是{count}</h2> <button onClick={()=>dispatch(‘add‘)}>Increment</button> <button onClick={()=>dispatch(‘sub‘)}>Decrement</button> </div> ) } export default ReducerDemo
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b])
;主要用来解决使用React hooks产生的无用渲染的性能问题,功能类似于shouldCompnentUpdate。function ChildComponent({name,children}){ function changeXiaohong(name){ console.log(‘她来了,她来了。小红向我们走来了‘) return name+‘,小红向我们走来了‘ } const actionXiaohong = useMemo(()=>changeXiaohong(name),[name]) return ( <> <div>{actionXiaohong}</div> <div>{children}</div> </> ) }
const refContainer = useRef(initialValue);useRef
返回一个可变的 ref 对象,其 .current
属性被初始化为传入的参数(initialValue
)。返回的 ref 对象在组件的整个生命周期内保持不变。
function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` 指向已挂载到 DOM 上的文本输入元素 inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
参考文章:
https://jspang.com/detailed?id=50
https://zh-hans.reactjs.org/docs/hooks-reference.html
标签:sem isp inpu const nbu ext pre containe org
原文地址:https://www.cnblogs.com/dadouF4/p/12342516.html