美文网首页
react useRef and hooks

react useRef and hooks

作者: noyanse | 来源:发表于2020-06-25 16:01 被阅读0次

useRef 多次渲染之间的纽带

在所有render中都保持唯一的引用,对REF的赋值和取值
拿到的都是最终的状态,不会在不同的render之间存在隔离

修改ref的值不会重新render

在组件更新时触发

const didMountRef = useRef(false)
useEffect(() => {
    if (didMountRef.current) {
        console.log('this is updated')
    } else { // first
        didMountRef.current = true
    }
})

访问dom节点

const domRef = useRef<HTMLInputElement>(null)

useEffect(() => {
    if (domRef && domRef.current) {
        domRef.current.focus()
    }
}) 

render (
    <>
        <input ref={domRef} />
    </>
)

useContext 解决多层传递属性

父组件:

interface IThemeProps {
    [key: string]: {color: string; background: string}
}
const themes: IThemeProps = {
    'light': {
        color: '#000',
        background: '#eee'
    },
    'dark': {
        color: '#fff',
        background: '#222'   
    }
}
export const ThemeContext = React.createContext(themes.light)// 给个默认值
return (
    <ThemeContext.Provider value={theme.light}>
        // 只要被包裹的组件都可以使用这个props
    </ThemeContext.Provider>
)

子孙组件:

const theme = useContext(ThemeContext)
console.log(theme)
const style = {
    background: theme.background,
    color: theme.color
}
console.log(style)

Hook 规则 和 其他hook

https://usehooks.com/

规则:

  1. 只在最顶层使用hook
    不要在条件或者嵌套函数中使用,确保在react函数的最顶层调用
    能够确保hooks在每一次渲染中都按照相同顺序调用
  2. 只在React函数中调用Hook

其他hook

  1. useReducer 为了简化复杂的useState, 之后可能会使用redux了
  2. useCallback 为了性能调优, 可以在多次渲染中记住某个函数,再次渲染不需要新建对象

相关文章

网友评论

      本文标题:react useRef and hooks

      本文链接:https://www.haomeiwen.com/subject/xqbsfktx.html