React 16.8.6 Hooks小结


1.useEffect 模拟 componentDidmunt:

useEffect(() => { document.title = `XXXX`; // 数据请求 }, [])

2.模拟 componentDidUpdate:

useEffect(() => { // 处理 }, [props属性])  // 自己浅对比

3.模拟 componentWillunmunt:

useEffect(() => {

return () => { console.log('2222'); };

}, [])

注:useEffect目前不支持Pre-render lifecycle events(getDerivedStateFromProps,componentWillReceiveProps)

父级调用子级的方法:

子级(list.tsx):

import React, { useImperativeHandle, forwardRef } from 'react'

const List: React.SFC<ListProps> = (props, ref) => {
// 某方法
const test = () =>{
 console.log('111')
}
// 开放Api
useImperativeHandle(ref, () => ({
  test,
}))
return (<div>我是子级</div>)

}

export default forwardRef(List)

父(index.tsx):

import React, { useRef } from 'react'
import List from './List'

const Parent: React.SFC<indexProps> = (props) => {
let chidrenfun: React.RefObject
<unknown> = useRef()
const testFun
= () => { childrenfun.current.test() // 输出111 }
return (
<div>   <div onClick={testFun}>点击测试</div>   <List ref={childrenFun} /> </div>
) }

 注: 在function组件中 useRefcreateRef靠谱,useRef只会把初始渲染的实例化返回。在基于类的组件中,createRef将始终创建新的ref。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM